substring with concatenation
1 class Solution { 2 public: 3 vector<int> findSubstring(string S, vector<string> &L) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<int> v; 7 if( L.empty() ) return v; 8 int wn = L.size(); 9 int wl = L[0].size(); 10 if( S.length() < wn*wl ) return v; 11 map<string,int> count; 12 for(int i=0;i<wn;i++) 13 { 14 if( count.find(L[i])!=count.end()) 15 count[L[i]] ++; 16 else 17 count[L[i]] = 1; 18 } 19 map<string,int> found; 20 int fn; 21 for(int i=0;i<wl;i++) 22 { 23 fn = 0; 24 for(int j=i;j+wl<=S.length();j+=wl) 25 { 26 if( j+wl*(wn-fn) > S.length() ) 27 break; 28 string str = S.substr( j,wl); 29 if( count.find(str)!=count.end() ) 30 { 31 if(found.find(str)!=found.end()) 32 { 33 found[str] ++; 34 if( found[str] > count[str] ) 35 { 36 int k = j - wl*fn; 37 string s; 38 while(k<j && (s = S.substr( k,wl))!=str) 39 { 40 found[s] --; 41 fn --; 42 if( found[s] == 0 ) 43 found.erase( s ); 44 k += wl; 45 } 46 found[str] --; 47 } 48 else 49 fn++; 50 if( fn == wn ) 51 v.push_back( j - (wn-1)*wl ); 52 } 53 54 else 55 { 56 found[str] = 1; 57 fn++; 58 if( fn == wn ) 59 v.push_back( j - (wn-1)*wl ); 60 } 61 } 62 else 63 { 64 found.clear(); 65 fn = 0; 66 } 67 68 } 69 } 70 return v; 71 72 } 73 };
posted on 2013-09-06 17:05 jumping_grass 阅读(162) 评论(0) 收藏 举报
浙公网安备 33010602011771号