From 6ab678a213f168d40fdae25cc5411e413093304f Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Tue, 15 May 2018 23:02:22 +0100 Subject: [PATCH] simple_wildcard_match.cpp --- .../training/simple_wildcard_match.cpp | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 puzzles/interviews/training/simple_wildcard_match.cpp diff --git a/puzzles/interviews/training/simple_wildcard_match.cpp b/puzzles/interviews/training/simple_wildcard_match.cpp new file mode 100644 index 0000000..2571ec5 --- /dev/null +++ b/puzzles/interviews/training/simple_wildcard_match.cpp @@ -0,0 +1,94 @@ +/* +VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I." +VIM: let b:wcppflags="/O2 /EHsc /DWIN32" +VIM-: let b:cppflags=g:Iboost.g:Itbb +VIM-: let b:ldflags=g:Lboost.g:Ltbb +VIM-: let b:ldlibpath=g:Bboost.g:Btbb +VIM-: let b:argv="" +*/ +#include +#include +#include +#include + +/* +Simple wildcard match. + +*/ + +bool wildcard_match(const std::string& input, const std::string& pattern) +{ + int j = 0; + int i = 0; + int restart_idx = -1; + while ( i < input.size() ) + { + while ( j < pattern.size() && pattern[j] == '*' ){ + restart_idx = ++j; + } + if ( j= 0 && pattern[j-1] == '*' ) { + ++i; + } + else if ( restart_idx > 0 ) { + i -= j - restart_idx -1; + j = restart_idx; + } + else { + return false; + } + } + while ( j < pattern.size() && pattern[j] == '*' ){ + ++j; + } + return j == pattern.size(); +} + +void test(const std::string& input, const std::string& pattern) +{ + std::cout << input << " x " << pattern + << " == " << wildcard_match(input,pattern) + << std::endl; +} + + +int main ( void ) +{try{ + auto begin = std::chrono::high_resolution_clock::now(); + + test("zebra", "dog"); + test("zebra", "zebra"); + test("zebra", "*br*"); + test("zebra", "*bi*"); + test("zebra", "*br*a"); + test("zebra", "*br*b"); + test("zebra", "z**a"); + test("zebra", "z*a"); + test("zebra", "x**a"); + test("zebrabrb", "*brb*"); + test("zebra", "*bra*"); + test("zebrazebrazebra", "*bra*zeb*zeb*"); + test("zebrbzebrazebra", "*bra*zeb*zeb*"); + test("zebrbzebrazebra", "*bra*zeb*"); + + auto end = std::chrono::high_resolution_clock::now(); + std::chrono::duration seconds = end - begin; + std::cout << "Time: " << seconds.count() << std::endl; + return 0; +} +catch ( const std::exception& e ) +{ + std::cerr << std::endl + << "std::exception(\"" << e.what() << "\")." << std::endl; + return 2; +} +catch ( ... ) +{ + std::cerr << std::endl + << "unknown exception." << std::endl; + return 1; +}} +