自己想的大体思路还是对的,不过可以改进的很多,最后网上找了个勉勉强强过large的答案,用map实在太容易超时了。。
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 int len = L[0].size(); 7 int size = L.size(); 8 map<string, int> T; 9 map<string, int> V; 10 for (int i = 0; i < L.size(); i++) T[L[i]]++; 11 vector<int> ret; 12 for (int i = 0; i < S.size()-size*len+1; i++) { 13 V.clear(); 14 int j = 0; 15 for (; j < size; j++) { 16 string tmp = S.substr(i+j*len, len); 17 if (T.find(tmp) != T.end()) V[tmp]++; 18 else break; 19 if (V[tmp] > T[tmp]) break; 20 } 21 if (j == size) ret.push_back(i); 22 } 23 return ret; 24 } 25 };
C#
1 public class Solution { 2 public List<int> FindSubstring(string s, string[] words) { 3 int len = words[0].Length; 4 int size = words.Length; 5 Dictionary<string, int> T = new Dictionary<string, int>(); 6 Dictionary<string, int> V = new Dictionary<string, int>(); 7 for (int i = 0; i < size; i++) { 8 if (T.ContainsKey(words[i])) T[words[i]]++; 9 else T.Add(words[i], 1); 10 } 11 List<int> ans = new List<int>(); 12 for (int i = 0; i < s.Length-size*len+1; i++) { 13 V.Clear(); 14 int j = 0; 15 for (; j < size; j++) { 16 string tmp = s.Substring(i+j*len, len); 17 if (T.ContainsKey(tmp)) { 18 if (V.ContainsKey(tmp)) V[tmp]++; 19 else V.Add(tmp, 1); 20 } 21 else break; 22 if (V[tmp] > T[tmp]) break; 23 } 24 if (j == size) ans.Add(i); 25 } 26 return ans; 27 } 28 }