LeetCode Substring with Concatenation of All Words

本文介绍了一种用于查找字符串S中所有由字符串列表L组成的子串起始索引的方法。通过使用HashMap来跟踪L中的字符串及其出现次数,该算法能够有效地找到所有符合条件的子串,并返回它们的起始位置。

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

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).

L中的字符串可能会重复,使用hashmap记录

由于L中字符串长度一致,可以使用substring方法提取子串,判断L中是否存在,循环n次

public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        ArrayList<Integer>res=new ArrayList<Integer>();
        HashMap<String,Integer>words=new HashMap<String,Integer>();
        HashMap<String,Integer>now=new HashMap<String,Integer>();
		int n=L.length;
		int tmp;
        if(n==0)
        	return res;
        for(int i=0;i<n;i++){
        	if(words.containsKey(L[i])){
        		tmp=words.get(L[i]);
        		tmp++;
        		words.put(L[i], tmp);
        	}
        	else
        		words.put(L[i], 1);
        }
        int len=L[0].length();
        int l=S.length();
        for(int i=0;i<=l-n*len;i++){
        	now.clear();
        	int j;
        	for(j=0;j<n;j++){  //n次循环判断
        		String word=S.substring(i+j*len, i+j*len+len);  //截取子串
        		if(words.containsKey(word)){   //是否包含
        			if(now.containsKey(word)){
                		tmp=now.get(word);
                		tmp++;
                		now.put(word, tmp);
                	}
                	else
                		now.put(word, 1);
        			if(now.get(word)>words.get(word))   //判断次数是否超过
        				break;
        		}
        		else break;
        	}
        	if(j==n)
        		res.add(i);
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值