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 wordsexactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9]
.
题意 :给出一个字符串和字符串数组,求字符串数组组成的字符串在字符串的索引位置
思路:先求出字符串数组的hashMap,在遍历字符中时,截取对应长度的字符串,看这个字符串是否由hashMap中的key全部组成。
代码如下:
class Solution
{
private boolean lookup(String s, Map<String, Integer> wordMap, int wordlen)
{
Map<String, Integer> tmpMap = new HashMap<String, Integer>();
for (int i = 0; i < s.length(); i += wordlen)
{
String tmp = s.substring(i, i + wordlen);
if (!wordMap.containsKey(tmp)) return false;
if (tmpMap.containsKey(tmp))
{
if (tmpMap.get(tmp) == wordMap.get(tmp)) return false;
tmpMap.put(tmp, tmpMap.get(tmp) + 1);
}
else
{
tmpMap.put(tmp, 1);
}
}
return true;
}
public List<Integer> findSubstring(String s, String[] words)
{
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (String word : words)
{
if (wordsMap.containsKey(word))
{
wordsMap.put(word, wordsMap.get(word) + 1);
}
else
{
wordsMap.put(word, 1);
}
}
int wordnums = words.length;
int wordlen = words[0].length();
List<Integer> ans = new ArrayList<Integer>();
for (int i = 0; i + wordnums * wordlen - 1 < s.length(); i++)
{
String substr = s.substring(i, i + wordnums * wordlen);
if (lookup(substr, wordsMap, wordlen))
{
ans.add(i);
}
}
return ans;
}
}