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"]


给定一个字符串s及一个字符串数组words,找到所有位置index,这些s.substring(index,index+words[0].length()*words.length)包含了所有words的词组,例如barfoothefoobarman 的0-5包含"foo", "bar"这些就符合要求。

由于words里面的单词,每个单词长度一样,可以重复,所以还是要用map记录每个词出现的次数,所以先构造关于words的map<String,Integer>

然后每次从s中取words所有词总长度相等的子串,然后去map中匹配即可。

这种方法效率一般,要注意循环里避免new对象


public List<Integer> findSubstring(String s, String[] words) {
         	List<Integer> result = new ArrayList<Integer>();
			  if(s==null||words==null||words.length<1||words[0].length()*words.length>s.length())
				  return result;
			 Map<String ,Integer> map = new HashMap<String ,Integer>();
			 for(int i=0;i<words.length;i++){
				 if(map.containsKey(words[i])){
					 map.put(words[i], map.get(words[i])+1);
				 }
				 else{
					 map.put(words[i], 1);
				 }
			 }
			 int len = words[0].length();
			 for(int i=0;i+words.length*len<=s.length();i++){
				  if(isMatch(s.substring(i,i+words.length*len),map,len ))
					  result.add(i);
					
			 }
				
		      return result;  
		    }
		  
		  public static boolean isMatch(String s,Map<String ,Integer> map,int len) {
			   Map<String ,Integer> tempMap = new HashMap<String ,Integer>(map);
			for(int i=0;i*len<s.length();i++){
				String str = s.substring(i*len, i*len+len);
				if(!tempMap.containsKey(str)|| tempMap.get(str)<1){
					return false;
				}
				else
					tempMap.put(str, tempMap.get(str)-1);
			}
			return true;
			  
		  }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值