leetcode - Substring with Concatenation of All Words
2013-12-16 21:12 张汉生 阅读(180) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 typedef unordered_map<string,int> HashMap; 4 bool canMatch(const char* head, const char * end, HashMap & flags, int l){ 5 if (head == end+1) 6 return true; 7 string s=""; 8 for (int i=0; i<l; i++) 9 s+= *(head+i); 10 HashMap::iterator hi = flags.find(s); 11 if (hi==flags.end() || hi->second<=0) 12 return false; 13 flags[s]--; 14 bool rlt = canMatch(head+l,end,flags,l); 15 flags[s]++; 16 return rlt; 17 } 18 vector<int> findSubstring(string S, vector<string> &L) { 19 // IMPORTANT: Please reset any member data you declared, as 20 // the same Solution instance will be reused for each test case. 21 vector<int> rlt; 22 int n = L.size(); 23 if (n<=0) 24 return rlt; 25 int l = L[0].length(); 26 if (l<=0) 27 return rlt; 28 HashMap flags; 29 for (int i=0; i<n; i++){ 30 if (flags.find(L[i]) == flags.end()) 31 flags[L[i]]=1; 32 else flags[L[i]]++; 33 } 34 const char * head = S.c_str(); 35 for (int i=0; i+l*n<=S.length(); i++){ 36 if (canMatch(head+i, head+i+l*n-1, flags, l)) 37 rlt.push_back(i); 38 } 39 return rlt; 40 } 41 };