LeetCode_OJ【30】Substring with Concatenation of All Words

本文介绍了一种利用滑动窗口思想寻找字符串中所有由指定单词列表组成的子串的方法,并给出具体实现代码。

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

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) ins that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

这道题目主要是运用滑动窗口的思想。

首先设置一个Map<String,int> (记作need)记录words中所有的字符串,Map<String,int> (记作has)则表示当前遍历的情况。

设words中的任一一个字符串的长度为len,则i从0到len,对于每个i,分别看s在[i,i+len] ,[i+len,i+2*len]........的子串,是否符合要求,符合要求就添加到has中。

内层循环的时间复杂度为O(n/len),外层循环的时间复杂度为O(len),所以总的时间复杂度为O(n)。

代码如下:

public class Solution {
	public List<Integer> findSubstring(String s, String[] words) {
		List<Integer> res = new ArrayList<Integer>();
		if(s == null || s.length() == 0 || words == null || words.length == 0)
			return res;
		HashMap<String, Integer> need = new HashMap<String, Integer>();
		HashMap<String, Integer> has = new HashMap<String, Integer>();
		for(int i = 0; i < words.length; i ++){
				if(need.containsKey(words[i]))
					need.put(words[i], need.get(words[i])+1);
				else
					need.put(words[i],1);
		}
		int len = words[0].length();
		for(int i = 0; i < len ; i++){
			int start = i;
			int cur = i;
			while(start <= s.length() - words.length *len && cur <= s.length() -len){
				String str = s.substring(cur,cur+len);
				if(need.containsKey(str)){
					if(has.containsKey(str) && has.get(str) == need.get(str)){
						String tmp = s.substring(start,start+len);
						has.put(tmp, has.get(tmp)-1);
						start += len;
						continue;
					}
					else if(!has.containsKey(str)){
						has.put(str, 1);
					}
					else{
						has.put(str, has.get(str)+1);
					}
					cur += len;
					if(cur - start == words.length*len){
						res.add(start);
						String tmp = s.substring(start,start+len);
						has.put(tmp, has.get(tmp)-1);
						start += len;
					}
				}
				else{
					has.clear();
					cur += len;
					start = cur;
				}
			}
			has.clear();
		}
		return res;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值