思路: 遍历s,找出长度符合的substrings,然后将substring和word做比较。怎么比较呢?我们可以利用Arrays.sort()。不过首先substring需要按照每个word的长度先分割一下,组成一个数组。然后将这个数组与words数组都做Arrays.sort()操作,操作完之后,两个数组应该是完全相等的,这样的话我们就找到了一个valid substring。下面展示代码:
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> list = new ArrayList<>();
Map<String,Boolean> mappings = new HashMap<>();
Arrays.sort(words);
if(words.length == 0){return list;}
int singleLen = words[0].length();
int wordsLen = singleLen * words.length;
for(int i = 0; i <= s.length() - wordsLen; i++){
String str = s.substring(i,i+ wordsLen);
if(mappings.containsKey(str) && mappings.get(str) == true){list.add(i);continue;}
if(mappings.containsKey(str) && mappings.get(str) == false){continue;}
String[] sss = stringSplit(str,singleLen);
Arrays.sort(sss);
if(Arrays.equals(words,sss)){
list.add(i);
mappings.put(str,true);
}else{
mappings.put(str,false);
}
}
return list;
}
public String[] stringSplit(String s, int spiltNum) {
int startIndex = 0;
int endIndex = spiltNum;
int lenght = s.length();
List<String> subs = new ArrayList<>();
boolean isEnd = true;
while (isEnd){
if(endIndex >= lenght){
endIndex = lenght;
isEnd = false;
}
subs.add(s.substring(startIndex,endIndex)) ;
startIndex = endIndex;
endIndex = endIndex + spiltNum;
}
String[] sss = subs.toArray(new String[subs.size()]);
return sss;
}
}
总结:
- Arrays.sort(Object[]);
- Arrays.equals(array1,array2);