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].
(order does not matter).
题目意思: 输入字符串S和列表L,L含有一组长度相同的单词。找出所有子串的开始下标,该子串由L的所有单词拼接而成,而且没有夹杂其他字符
public class Solution {
public List<Integer> findSubstring(String S, String[] L) {
Map<String, Integer> dict = new HashMap<String, Integer>();
for (String l : L) {
if (!dict.containsKey(l)) {
dict.put(l, 0);
}
dict.put(l, dict.get(l)+1);
}
int len = L[0].length();
int lenSum = len*L.length;
List<Integer> list = new ArrayList<Integer>();
for (int i=0; i<=S.length()-lenSum; i++) {
Map<String, Integer> dictCopy = new HashMap<String, Integer>(dict);
boolean flag = true;
for (int j=i; j<i+lenSum; j=j+len) {
String s = S.substring(j, j+len);
Integer num = dictCopy.get(s);
if (num==null || num==0) {
flag = false;
break;
}
num--;
dictCopy.put(s, num);
}
if (flag) {
list.add(i);
}
}
return list;
}
}
本文提供了一个方法,用于在给定字符串中查找由一组特定单词组成的序列,并返回序列起始索引的集合。这种方法适用于处理文本分析、字符串匹配等任务。
411

被折叠的 条评论
为什么被折叠?



