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:
L:
S:
"barfoothefoobarman"L:
["foo", "bar"]
You should return the indices:
(order does not matter).
[0,9].(order does not matter).
Analysis:
一开始觉得非常复杂,找了几个别人的博客看。看了几天,没看懂。最后找到一个牛人的地址http://n00tc0d3r.blogspot.com/2013/06/substring-with-concatenation-of-all.html?view=classic 慢慢的就懂了。不过有些细节还是不太清楚,只有慢慢积累。
现在开始把代码写到Eclipse里面了。1.可以节约在LeetCode编码的时间. 2. LeetCode如果报错可以Debug。之前一旦LeetCode没通过要找n久的bug,效率实在太低。
时间和空间复杂度就暂时不讨论了,不懂。
Solution:
1: public class Solution {
2: public ArrayList<Integer> findSubstring(String S, String[] L){
3: ArrayList<Integer> res=new ArrayList<Integer>();
4: if(S==null||L==null)
5: return res;
6: HashMap<String,Integer> words=new HashMap<String,Integer>();
7: int wordLen=L[0].length(),total=L.length;
8: for(String s:L)//Store all words to hashmap
9: {
10: if(words.containsKey(s))
11: words.put(s, words.get(s)+1);
12: else
13: words.put(s, 1);
14: }
15: for(int i=0;i<=S.length()-wordLen*total;i++)
16: {
17: HashMap<String,Integer> curWords=new HashMap<String,Integer>(words);
18: for(int j=i;j<=S.length()-wordLen && !curWords.isEmpty();j+=wordLen)
19: {
20: String word=S.substring(j,j+wordLen);
21: if(!curWords.containsKey(word))
22: break;
23: else
24: {
25: if(curWords.get(word)>1)
26: curWords.put(word, curWords.get(word)-1);
27: else
28: curWords.remove(word);
29: }
30: }
31: if(curWords.isEmpty())
32: res.add(i);
33: }
34: return res;
35: }
36: }
没有评论:
发表评论