[Leetcode] Substring with Concatenation of All Words (Java)

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

题意:给定一个字符串S,并且给定一个单词集合L,每个单词长度相等。找到S的子串等于L所有单词的集合(每个单词出现且仅出现一次,但是L中单词允许重复),不含有别的字母(即若L=["ab","cd","ab"],那么找到的S子串可能为”abcdab“,”ababcd“,”cdabab“,但是”abccdab“与”abcd“则不行),找出所有这样的S子串,并返回每一个子串的初始坐标值。

hash的办法,若L=["ab","cd","ab"],则 map为:("ab",2),("cd",1)

从S中找是否含有所有的map内容,若中间出现多余单词或字母,则i++开始下次查找,若未出现其余字母与单词,则将i 加入到list中。

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

public class SubstringwithConcatenationofAllWords {
	public ArrayList<Integer> findSubstring(String S, String[] L) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		if(L.length<1)
			return list;
		int wordLen = L[0].length();
		Map<String, Integer> map = new HashMap<String, Integer>();
		for(String s : L) {
			if(!map.containsKey(s))
				map.put(s, 1);
			else {
				map.put(s, map.get(s)+1);
			}
		}
		boolean flag ;
		for(int i=0;i<=S.length()-L.length*wordLen;i++){
			int start = i;
			Map<String, Integer> temp = new HashMap<String, Integer>(map);
			flag = false;
			while(start-i<L.length*wordLen){
				flag = true;
				String string = S.substring(start,start+wordLen);
				if(temp.containsKey(string)&&temp.get(string)>0)
					temp.put(string, temp.get(string)-1);
				else {
					flag = false;
					break;
				}
				start+=wordLen;
			}
			if(flag){
				list.add(i);
			}
		}
		return list;
	}
	public static void main(String[] args) {
		String[] L = {"a","b"};
		String S = "aaa";
		for(Integer i : new SubstringwithConcatenationofAllWords().findSubstring(S, L)){
			System.out.print(i+",");
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值