您的位置:首页 > 其它

[LeetCode] Substring with Concatenation of All Words

2014-06-07 22:08 441 查看
利用Hash并求和的想法很早就想出来了,但是总是超时。主要是优化的方向不对,搞了个滑窗的机制,变复杂了而且效果不好。

public class Solution {
public List<Integer> findSubstring(String S, String[] L) {
ArrayList<Integer> result = new ArrayList<Integer>();

int totalLength = S.length();
int arrayLength = L.length;
int wordsLength = L[0].length();
int combinationLength = arrayLength * wordsLength;
if (totalLength == 0 || arrayLength == 0 || totalLength < combinationLength) {
return result;
}

HashSet<String> wordSet = new HashSet<String>();
int hashSum = 0;
for (String word : L) {
wordSet.add(word);
hashSum += word.hashCode();
}

for (int i = 0; i < totalLength - combinationLength + 1; ++i) {
String sub = S.substring(i, i + wordsLength);
if (!wordSet.contains(sub)) {
continue;
}

int tempHash = 0;
for (int j = 0; j < arrayLength; ++j) {
int start = i + j * wordsLength;
sub = S.substring(start, start + wordsLength);
if (!wordSet.contains(sub)) {
break;
}
else {
tempHash += sub.hashCode();
}
}
if (tempHash == hashSum) {
result.add(i);
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: