可能是2018 亚麻的OA题。
1.给字符串, 找出里面长度为N的, 并且里面字符只有一次重复的字串。
例子:s: asdfaghjkjqoiiii;N=5. 返回asdfa ghjkj hjkjq jkjqo jqoii.
1 #include <iostream> // std::cout 2 #include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap 3 #include <vector> // std::vector 4 #include <unordered_map> 5 #include <unordered_set> 6 #include <numeric> 7 #include <sys/time.h> 8 #include <list> 9 #include <map> 10 11 //main point : ( refer to key data structure and the trick ) 12 13 // use the two unordered set: dup and match 14 // dup : for check if the finded substring is already in result set , that means it has been found early. 15 // match: check if the substring has only one duplicated char. 16 17 //use list to store the results. 18 19 // iterate the string with N size window from first char to the end of the string. 20 21 22 using namespace std; 23 24 25 list<string> findNSubstring (string& s, int N){ 26 //check the input 27 if ( s.empty()|| s.size() < N ) return list<string>(); 28 29 int sp =0; 30 int steps = N-1; 31 cout << " the steps is " << steps << endl; 32 unordered_set<string> dup; //make sure no duplicated substring in result set. 33 unordered_set <char> match; // check the substring has only one duplicated char. 34 list<string> res; //store the output. 35 36 // Check the substrings one by one with N size window. 37 while ((sp+steps) < s.size()){ 38 match.clear(); 39 40 // check if the substring have only one duplicated character. 41 for (int j =0; j < N ; j++){ 42 match.insert(s[sp+j]); 43 } 44 45 if (match.size() == N-1){ // if yes, check if that substring has been in result set. 46 cout<< "find one " << s.substr( sp, N) << " at "<< sp << endl; 47 if ( dup.find( s.substr( sp, steps)) == dup.end()){ 48 res.push_back(s.substr( sp, N)); 49 dup.insert (s.substr( sp, N)); 50 } 51 } 52 sp++; 53 } 54 return res; 55 } 56 57 int main () { 58 59 // cout << " test a substring length : " << string ("").size() << endl; 60 61 //get the start time. 62 struct timeval tv; 63 gettimeofday(&tv,NULL); 64 long ts = tv.tv_sec * 1000 + tv.tv_usec / 1000; 65 66 //*** call the function . 67 68 string in = "iiiiiiiiiiiiiiiiiii";//asdfaghjkjqoiiii"; 69 70 int q = 100 ; 71 72 auto out = findNSubstring(in, q) ; 73 74 for (auto e : out) 75 cout<< e << endl; 76 //*** end of the call 77 78 //get the time of end. 79 gettimeofday(&tv,NULL); 80 long te = tv.tv_sec * 1000 + tv.tv_usec / 1000; 81 82 //output the time of the running. 83 cout<<endl<< endl<< "running tmie is : " << te - ts << endl; 84 return 0; 85 }
原文地址:https://www.cnblogs.com/HisonSanDiego/p/8295998.html
时间: 2024-11-26 01:53:36