LeetCode, leetcodeoj
Given a stringSAnd a dictionary of wordsDict, Determine ifSCan be segmented into a space-separated sequence of one or more dictionary words.
For example, given
S= "Leetcode ",
Dict= ["Leet", "code"].
Return true because "leetcode" can be segmented as "leet code ".
[Idea]
At the beginning, I tried to match the problem as much as possible, for example, s = "abcdefabc" dict = ["abc ", "def"] I only need to remove all words in s that exist in the dictionary. Finally, if s does not have any letters, it means it can be break;
But the problem arises. s = "aaaaaaa" dict = ["aaa", "aaaa"]. In this case, aaa is directly used to divide s into aaa, aaa, and; returns false.
For example, s = "abcdeefg" dict = ["AB", "cde", "ee", "cd", "fg"], when "cde" in the dictionary is used for segmentation, the result is AB, cde, e, fg; and false is returned.
[Dynamic Planning and problem solving]
[Key Points★★]
Starting from s [2] = c, we found that two dictionary words match, that is, cde, cd, weMark the length they can splice
AB cdeefg
AB
Cde
Cd
---> Next, we will start matching from the position of efg or eefg.
[Code]
1 public class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 boolean[] t = new boolean[s.length()+1]; 4 t[0] = true; //set first to be true, why? 5 //Because we need initial state 6 7 for(int i=0; i<s.length(); i++){ 8 //should continue from match position 9 if(!t[i]) 10 continue;11 12 for(String a: dict){13 int len = a.length();14 int end = i + len;15 if(end > s.length())16 continue;17 18 if(t[end]) continue;19 20 if(s.substring(i, end).equals(a)){21 t[end] = true;22 }23 }24 }25 26 return t[s.length()];27 }28 }