LeetCode Online Judge 题目C# 练习 - Substring with Concatenation of All Words
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).
1 public static List<int> SubstringwithConcatenationofAllWords(string S, List<string> L) 2 { 3 List<int> ret = new List<int>(); 4 Dictionary<string, int> map_count = new Dictionary<string, int>(); 5 Dictionary<string, int> map_found = new Dictionary<string, int>(); 6 int l = L[0].Length; 7 int total = L.Count; 8 9 //Add words in L to the map_count 10 for (int i = 0; i < total; i++) 11 { 12 if (map_count.ContainsKey(L[i])) 13 map_count[L[i]]++; 14 else 15 map_count.Add(L[i], 1); 16 } 17 18 //last index need to check 19 int last = S.Length - l * total; 20 for (int i = 0; i <= last; i++) 21 { 22 int index = i; 23 string sub = S.Substring(index, l); 24 for(int j = 0; j < total; j++) 25 { 26 if (!map_count.ContainsKey(sub)) 27 break; 28 else if (map_found.ContainsKey(sub) && map_found[sub] >= map_count[sub]) 29 break; 30 else 31 { 32 if (map_found.ContainsKey(sub)) 33 map_found[sub]++; 34 else 35 map_found.Add(sub, 1); 36 index += l; 37 sub = S.Substring(index, l); 38 } 39 40 if (j == total - 1) 41 { 42 ret.Add(i); 43 } 44 } 45 46 map_found.Clear(); 47 } 48 49 return ret; 50 }
代码分析:
这个代码过不了大数据,Time Limit Exceeded。 可能是SubString这个方法比较耗性能。
这个是别人用JAVA做的,能过大数据,先往下复习,回头再看 http://heartfire.cc/wp/substring-with-concatenation-of-all-words/