"030-substring with concatenation of all Words (concatenation of all words in a substring)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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 that's 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).
Main Topic
Given a string of s and a string array words,wrods the length of the string is equal, find out that all the substrings in s are exactly the same as all the characters in the words, and return the starting position of the substring.
Thinking of solving problems
Turn the words into a hashmap
Code Implementation
Algorithm implementation class
Import java.util.*; Public classSolution { PublicList<integer> findsubstring (StringSString[] words) {list<integer> List =NewArraylist<integer> ();if(Words.length = =0) return list;intWlen = words[0].length ();int Len= S.length ();if(Len< Wlen * Words.length) return list; map<String, integer> MAPW =Newhashmap<String, integer> (); for(Stringword:words) mapw.put (Word, mapw.containskey (word)? MAPW.Get(word) +1:1); for(intStart =0; Start < Wlen; start++) {intpos = start;intTstart =-1; map<String, integer> mapt =Newhashmap<String, integer> (MAPW); while(pos + Wlen <=Len) {StringCand = s.substring (pos, pos + wlen);if(!mapw.containskey (cand)) {if(Tstart! =-1) MapT =Newhashmap<String, integer> (MAPW); Tstart =-1; }Else if(Mapt.containskey (cand)) {Tstart = Tstart = =-1? Pos:tstart;if(MAPT.Get(cand) = =1) Mapt.remove (cand);ElseMapt.put (Cand, MapT.Get(cand)-1);if(MAPT.IsEmpty()) List.add (Tstart); }Else{ while(Tstart < POS) {StringRcand = s.substring (Tstart, Tstart + Wlen);if(Cand.equals (Rcand)) {Tstart + = Wlen;if(MAPT.IsEmpty()) List.add (Tstart); Break } Tstart + = Wlen; Mapt.put (Rcand, Mapt.containskey (rcand)? mapt.Get(Rcand) +1:1); }} pos + = Wlen; }} return list; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47064933"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
leetcode-Interview Algorithm classic-java Implementation "" 030-substring with concatenation of all Words (concatenation of all words in a substring) "