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).
题目大意为 给定一个字符串,和一个字符串数组,需要返回一个该字符串的索引组成的数组,返回的索引有如下性质:从每个索引开始,长度为L的字串需要精确包含字符串数组中的所有字符串。
这道题题目有点绕,大体的解题思路是将字符串数组words中的字符串都存入HashMap中,通过map的键去匹配字符串s中的字符串,如果匹配成功则count加1,直到count等于字符串数组的长度时即找到了一组符合的解。代码如下:
public List<Integer> findSubstring(String S, String[] L) {
List<Integer> ret = new ArrayList<Integer>();
int slen = S.length(), llen = L.length; //分别获取字符串和字符数组的长度
if (slen <= 0 || llen <= 0)
return ret;
int wlen = L[0].length(); //获取字符串数组中字符串的长度
//
HashMap<String, Integer> words = new HashMap<String, Integer>();//用于存放字符串数组中的字符串
//把字符串数组中的字符串都存入哈希表中
for (String str : L) {
if (words.containsKey(str)) { //判断words中是否有该键值,若有则数量加1;没有初始化为1,并放入哈希表中
words.put(str, words.get(str) + 1);
} else {
words.put(str, 1);
}
}
//
for (int i = 0; i < wlen; ++i) {
int left = i, count = 0; //left设置左边的起始位置,count用于记录L中的字符串在S中出现的次数变量
HashMap<String, Integer> tmap = new HashMap<String, Integer>();//用于存放字符串S中和字符串数组L中的字符串 相同的子串()
for (int j = i; j <= slen - wlen; j += wlen) {
String str = S.substring(j, j + wlen);//切割获得与字符串数组中等长的字符串
if (words.containsKey(str)) {//判断是否有和words中键值相同的字符串
//将相同字符串存入tmap哈希表中(将整个s串中所有相同的都存了进去)
if (tmap.containsKey(str)) {
tmap.put(str, tmap.get(str) + 1);
} else {
tmap.put(str, 1);
}
if (tmap.get(str) <= words.get(str)) { //比较该字符串在两个哈希表中出现的次数
count++;
} else { //大于说明在字符串S中已经出现了超过字符串数组中相同的字符串的出现数量,把最左边的字符串取出继续判断
while (tmap.get(str) > words.get(str)) {
String tmps = S.substring(left, left + wlen);
tmap.put(tmps, tmap.get(tmps) - 1);
if (tmap.get(tmps) < words.get(tmps)) {
count--;
}
left += wlen;
}
}
if (count == llen) {//count和字符串数组长度相等时,表示找到了字符串数组中所有字符串一次
ret.add(left);
String tmps = S.substring(left, left + wlen);
tmap.put(tmps, tmap.get(tmps) - 1);//把前一个字符串取出,继续向后找
count--;
left += wlen;
}
} else { //中间有不匹配的字符串则清空tmap和count,重新开始查找
tmap.clear();
count = 0;
left = j + wlen;
}
}
}
return ret;
}