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).
题目:给出一个字符串和一个字符串数组(其中每个字符串长度相等),数组中的字符串组成一个长串,找出字符串中和长串相等的子串,并输出其初始位置。
思路:因为字符串数组中每个元素长度都相等,就可以知道我们目标子串的长度。题目就简化成一个确定长度的字符串和一个数组中元素随机组成的串是否相等,那就可以把这个字符串也分割n个元素的数组,两个数组按顺序排列后比较是否相等即可。
public List<Integer> findSubstring(String s, String[] words) {
int len = words[0].length()*words.length;//数组元素个数*每个长度
List<Integer> list = new ArrayList<Integer>();
List<String> list1 = new ArrayList<String>();
for(int i = 0; i < words.length;i++) {
list1.add(words[i]);//把数组中的元素都放到list中,后面减小遍历范围有用
}
for(int i = 0;i <= s.length() - len;i++){
String str = s.substring(i, i + len);//把字符串按len长度分割,如果就这样去判断会超时,因此要排除一些子串,缩小范围
if(list1.contains(str.substring(0, words[0].length()))){//把那些开头就不符合的串给排除。
if(find(str, words)){
list.add(i);
}
}
}
return list;
}
public boolean find(String str, String[] words) {
String[] strWords = new String[words.length];
int len = words[0].length();
Arrays.sort(words);//数组按序排列
for(int i = 0; i < str.length()/len;i++){//把字符串分割,组成一个数组(根据words数组元素的长度来分割)
strWords[i] = str.substring(i*len, i*len+len);
}
Arrays.sort(strWords);//两个数组排序后比较
for(int i = 0; i< words.length;i++){
if(!words[i].equals(strWords[i])){
return false;
}
}
return true;
}

本文介绍了一种用于查找字符串数组在目标字符串中所有匹配子串起始位置的算法。该算法通过预处理字符串数组并利用排序比对的方式提高查找效率。
300

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



