You is given a string, s, and a list of words, words, that is all of the same length. Find all starting indices of substring (s) in S, a concatenation of each word in wordsexactly once and without any I ntervening characters.
For example, given:
S"barfoothefoobarman"
Words["foo", "bar"]
You should return the indices: [0,9] .
(Order does not matter).
Public classSolution { PublicList<integer>findsubstring (String s, string[] words) {//The test instructions is: given a string s and a string array words,words the length of each string is equal. //Find all the substrings in s that contain exactly all the characters in the words, returning the substring starting position. //The topic is very difficult, attention eye, words the string is equal length. //using the HASHMAP data structure, key holds the string in words, and value holds the number of occurrences of the string in words (note the processing of the repeating string)//when traversing s, the length of each substring substring is fixed. Defines a counter that adds results when the counter equals the number of words in words. //Notice the emptying of the HashMap and the method of judging the number of substrings using it .//Problem Solving steps://1. Use map to indicate that key in Words,map is the string in words, and value is the number of occurrences of the string//2. Execute the loop, using STR to denote the strings in S, CNT represents the number of strings in L contained in S. If the key in the map contains str and the corresponding value is greater than 0 (because it contains exactly 1 times),//the CNT//the value--。 for STR in ++,MAP If Cnt==words.length,//then this paragraph satisfies the question request. Then initialize the map again to continue the loop//3. Return result set intLen=words[0].length (); if(s==NULL|| S.length () <1)return NULL; List<Integer> res=NewArraylist<integer>(); Map<String,Integer> map=NewHashmap<string,integer>(); for(inti=0;i<words.length;i++){ if(Map.containskey (Words[i])) {Map.put (Words[i],map.get (words[i) )+1); }Else{map.put (words[i],1); } }//Note the range of I for(intI=0;i<=s.length ()-words.length*len;i++){ intFrom=i; intCon=0; /*String str=s.substring (From,from+len); while (Map.containskey (str) &&map.get (str) >0) {map.put (Str,map.get (str)-1); con++; if (con==words.length) {res.add (i); Break } From+=len; Str=s.substring (From,from+len); }*/ for(intj=0;j<words.length;j++){ //if ((from+ (j+1) *len) >s.length ()) break;String temp=s.substring (from+j*len,from+ (j+1) *Len); if(Map.containskey (temp) &&map.get (temp) >0) {map.put (Temp,map.get (temp)-1); Con++; }Else{ Break; } } if(con==words.length) {Res.add (i); } //Note Clear Map if(con>0) {map.clear (); for(intt=0;t<words.length;t++){ if(Map.containskey (words[t])) {Map.put (Words[t],map.get (words[t) )+1); }Else{map.put (words[t],1); } } } } returnRes; }}
[Leecode 30] Substring with concatenation of all Words