您的位置:首页 > 编程语言 > Java开发

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

2017-07-20 12:16 309 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: