您的位置:首页 > 其它

LeetCode29: Substring with Concatenation of All Words

2013-02-24 12:28 281 查看
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).
public class Solution {
public ArrayList<Integer> findSubstring(String S, String[] L) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<String, Integer> words = new HashMap<String, Integer>();
HashMap<String, Integer> found = new HashMap<String, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();

if(S==null || L==null)
return res;
// count all words in input list
for(String str:L){
if(words.get(str) == null)
words.put(str, 1);
else
words.put(str, words.get(str)+1);
}

int N=S.length();
int M=L.length;
int wordLen = L[0].length();

for(int i=0; i<=N-M*wordLen; i++){
found.clear();
int j;
for(j=0; j<M; j++){
String curStr = S.substring(i+j*wordLen, i+(j+1)*wordLen);
if(words.get(curStr) == null)
break;
int expectedCount = words.get(curStr);
int foundCount = found.get(curStr)==null?1:found.get(curStr)+1;
if(expectedCount<foundCount)
break;
found.put(curStr, foundCount);
}
if(j==M)
res.add(i);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: