[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; } }
相关文章推荐
- [Leetcode] Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words暴力法暴力法更加暴力的方法
- [LeetCode]Substring with Concatenation of All Words
- LeetCode Online Judge 题目C# 练习 - Substring with Concatenation of All Words
- leetcode 102: Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words 解题报告
- LeetCode:Substring with Concatenation of All Words
- leetcode_Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- LeetCode:Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- [LeetCode]Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- leetcode 71: Substring with Concatenation of All Words
- LeetCode: Substring with Concatenation of All Words
- LeetCode 笔记系列七 Substring with Concatenation of All Words
- leetcode -- Substring with Concatenation of All Words
- leetcode: Substring with Concatenation of All Words
- LeetCode : Substring with Concatenation of All Words