LeetCode 30 - Substring with Concatenation of all words

【题目】

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

给定一个字符串s,和一个字符串数组words,在字符串数组中的每一个单词都出现并仅出现一次的情况下,产生若干个新的字符串,判断新字符串是否存在于原字符串中,如果存在,输出首字母所在的下标

【思路】

采用滑动窗口机制进行解题,设数组的长度为length,单词的长度为distance

首先维护一个单次字典,用map实现,键为数组中的单词,值为数组中单词出现的次数,若滑动窗口中出现相应的字符串,则对应的值减去1;

滑动窗口的初始大小为0,窗口的左边界不变,右边界向右滑动distance个单位,若当前窗口中新增加的字符串出现在字典中,且值>0, 继续向右滑动distance个单位,若值=0,或者没有出现在字典中,则左窗口向右滑动一个单位,窗口大小重新变为0 ,初始化字典。

若当前窗口中的字符串长度 = length*distance,则表示找到了一个正确的字符串,将窗口的左下标存入结果中,左窗口向右滑动一个单位,窗口大小重新变为0,初始化字典。

【Java代码】

public class Solution {
	public List<Integer> findSubstring(String s, String[] words){
		List<Integer> result = new ArrayList<Integer>();
		if(s == "" || words.length == 0)
			return null;
		else{
			int distance = words[0].length();
			int length = words.length;
			HashMap<String,Integer> dict_org = initDict(words);
			HashMap<String,Integer> dict = new HashMap<String,Integer>();
			dict.putAll(dict_org);
			for(int i = 0 ; i <= s.length() - distance * length ;){
				boolean change_flag = false;
				int curr_distance = 0;		//滑动窗口的大小
				String curr = s.substring(i+curr_distance,i+curr_distance+distance);
				while(dict.containsKey(curr) && dict.get(curr) > 0){
					curr_distance += distance;
					dict.put(curr, dict.get(curr)-1);
					change_flag = true;
					if(curr_distance == distance * length){		//找到一个subString
						result.add(i);
						break;
					}
					curr = s.substring(i+curr_distance,i+curr_distance+distance);
				}
				if(change_flag){
					dict.putAll(dict_org);
				}
				i += 1;
			}
			return result;
		}
	}
	
	public HashMap<String,Integer> initDict(String[] w){
		HashMap<String, Integer> dict = new HashMap<String,Integer>();
		for(int i = 0 ; i < w.length ; i++){
			if(dict.containsKey(w[i]))
				dict.put(w[i], dict.get(w[i])+1);
			else
				dict.put(w[i],1);
		}
		return dict;
	}
}

【改进空间】

由于特殊情况的存在,例如:

1、s  =  "wordgoodbestwordgoodbest", words = {"word","good","best"}  使得左窗口向右一次性滑动的最大距离为distance

2、s = "cccca", words = {"cc","ca"},使得左窗口向右一次性滑动的最大距离又缩短为1

导致上述思路中,左窗口只能以1为单位向右滑动,虽然没有超时,但明显会对运行时间造成很大的影响,希望有后续算法可以改进 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值