[LeetCode] Substring with Concatenation of All Words

本文介绍了一种使用哈希求和的方法来解决字符串匹配问题,并通过滑动窗口进行优化。该方法首先计算目标单词集合的哈希值总和,然后遍历主字符串,检查每个可能的子串是否存在于单词集合中,并验证其哈希值总和是否与目标总和相等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值