[LeetCode] Substring with Concatenation of All Words

来源:互联网 发布:gom引擎源码 编辑:程序博客网 时间:2024/05/26 15:58

利用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;    }}


0 0