Substring with Concatenation of All Words
大佬的代码:https://blog.csdn.net/Maybeno1314/article/details/100692030 代码很简洁,也很详细,值得学习和借鉴。
个人微改:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class substringWithConcatenationOfAllWords {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("please enter your String :");
String s = sc.nextLine();
System.out.println("please enter the size of your substring array :");
int m = sc.nextInt();
String str[] = new String[m];
System.out.println("please enter your substring :");
for(int i=0;i<m;i++) {
str[i]=sc.next();
}
List<Integer> hah = new ArrayList<>();
hah = findSubstring(s,str);
System.out.println(hah);
sc.close();
}
static List<Integer> findSubstring(String s,String[] words){
List<Integer> ans = new ArrayList<>();
int sLen = s.length();
int wordNum = words.length;
if(wordNum == 0) {
return ans;
}
int wordLen = words[0].length();
int windowLen = wordLen*wordNum;
HashMap<String,Integer> wordCount = new HashMap<String,Integer>();
for(String word:words) {
int val = wordCount.getOrDefault(word,0);
wordCount.put(word,val+1);
}
for(int i=0;i<sLen-windowLen+1;i++) {
int count=0;
HashMap<String,Integer> windowWord = new HashMap<>();
while(count<wordNum) {
String word = s.substring(i+count*wordLen,i+(count+1)*wordLen);
if(wordCount.containsKey(word)) {
int val = windowWord.getOrDefault(word,0);
windowWord.put(word,val+1);
if(windowWord.get(word)>wordCount.get(word)) {
break;
}
}else {
break;
}
count++;
}
if(count==wordNum) {
ans.add(i);
}
}
return ans;
}
}
测试结果:
please enter your String :
barfoothefoobarman
please enter the size of your substring array :
2
please enter your substring :
foo
bar
[0, 9]