First, the topic
1, examining
2. Analysis
Give a string s, a dictionary table dict, to determine whether S can be composed of strings in Dict, where the string in Dict can be used multiple times.
Second, the answer
1, Ideas:
Method One,
Use a DP array to record S from subscript 0 to the current subscript position to match correctly.
①, starting from subscript i = 1, in the dictionary sequence dict to find the correct match to S subscript i;
Public BooleanWordbreak (String s, list<string>worddict) { intLen =s.length (); Boolean[] f =New Boolean[Len+1]; f[0] =true;//F[i] = true:0 ~ i-1 is capable of matching. for(inti = 1; I <= Len; i++) { for(String str:worddict) {if(I-str.length () >= 0 && F[i-str.length ()]) { if(S.substring (I-str.length (), i). Equals (str)) {F[i]=true; Break; } } } }
Method Two,
Use a DP array to record S from subscript 0 to the current subscript position to match correctly.
Public BooleanWORDBREAK11 (String s, list<string>worddict) { intLen =s.length (); Boolean[] f =New Boolean[Len+1]; f[0] =true;//F[i] = true:0 ~ i-1 is capable of matching. for(inti = 1; I <= Len; i++) { for(intj = 0; J < I; J + +) { if(F[j] &&Worddict.contains (S.substring (J, i))) {F[i]=true; Break; } } } returnF[len]; }
Method Three,
With BFS + DP.
①, a DP array is used to record whether the current position matches correctly.
The node that takes the current breadth traversal of a queue record.
All strings of a Set storage dictionary are used to make it easier to compare substrings that contain S.
②, the lookup process can be seen as a graph, each time from a node to the BFS to find all the nodes, and fill the DP array is true, while the node is added to the queue, continue the BFS traversal.
Public BooleanWordBreak12 (String s, list<string>worddict) { intMax_len =-1; for(String word:worddict) Max_len=Math.max (Max_len, Word.length ()); Set<String> Worddictset =NewHashset<>(worddict); Queue<Integer> queue =NewLinkedlist<integer>(); Boolean[] visited =New Boolean[S.length ()]; Queue.add (0); while(!Queue.isempty ()) { intStart =Queue.remove (); for(intEnd = start + 1; End <= s.length () && end-start <= Max_len; end++) { if(Worddictset.contains (s.substring (Start, end)) &&! (End < S.length () &&Visited[end])) { if(End = =s.length ()) { return true; } queue.add (end); Visited[end]=true; } } } return false; }
139. Word Break