[leetcode]30. Substring with Concatenation of All Words@Java

https://leetcode.com/problems/substring-with-concatenation-of-all-words/#/description


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


package go.jacob.day720;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 30. Substring with Concatenation of All Words
 * 
 * @author Administrator
 * 
 *         题意:给定一个字符串S和一个字符串数组L,L中的字符串长度都相等, 找出S中所有的子串恰好包含L中所有字符各一次,返回子串的起始位置。
 *         该题与leetcode 3.Longest Substring Without Repeating Characters类似
 * 
 */
public class Demo1 {
	/*
	 * 超时边缘的解法:Runtime: 211 ms
	 */
	public List<Integer> findSubstring(String s, String[] words) {
		List<Integer> res = new ArrayList<Integer>();
		if (s == null || words == null || words.length * words[0].length() > s.length())
			return res;
		//map中的key是字符串,value记录字符串在words中出现的的次数
		Map<String,Integer> map=new HashMap<String,Integer>();
		Map<String,Integer> tmpMap=new HashMap<String,Integer>();
		int wordNum=words.length,wordLen=words[0].length();
		//考虑到words中可能会有重读的字符串
		for(int i=0;i<wordNum;i++){
			if(tmpMap.containsKey(words[i]))
				tmpMap.put(words[i], tmpMap.get(words[i])+1);
			else
				tmpMap.put(words[i], 1);
		}
		for(int i=0;i<=s.length()-wordNum*wordLen;i++){
			map.clear();
			//用空间换时间
			int index=i;
			int count=0;
			for(int j=0;j<words.length;j++){
				String temp=s.substring(index, index+wordLen);
				if(!tmpMap.containsKey(temp))
					break;
				if(map.containsKey(temp))
					map.put(temp, map.get(temp)+1);
				else
					map.put(temp, 1);
				if(map.get(temp)>tmpMap.get(temp))
					break;
				count++;
				index+=wordLen;
					
			}
			if(count==wordNum)
				res.add(i);
		}
		
		
		
		return res;
	}
}





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值