Given A string s and a Dictionary of words dict, determine if s can segmented into a space-s Eparated 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" .
Problem solving idea One:
Direct brute-force enumeration leads to tle, so it is necessary to record the previous results, that is, the idea of DP can be used, Java implementation is as follows:
Static public Boolean wordbreak (String s, set<string> worddict) {boolean[] dp = new Boolean[s.length () + 1];dp [0] = true;for (int i = 1; i < dp.length; i++) for (int j = i; J >= 0 &&!dp[i]; j--) if (Worddict.contains (s.substr ING (i-j, i))) dp[i] = Dp[i-j];return dp[dp.length-1];}
Two ways to solve problems:
Given that the following question is not available with DP, the brute force enumeration is definitely tle, so you can set up a Unmatch collection to store the substrings in s that have determined that the mismatch is not matched, thus avoiding duplicate checks, and the Java implementation is as follows:
Static public Boolean wordbreak (String s, set<string> dict) {return Wordbreak (S, Dict, New hashset<string> ()) ;} Static public Boolean Wordbreak (string s, set<string> dict,set<string> Unmatch) {for (string prefix:dict) {i F (s.equals (prefix)) return True;else if (s.startswith (prefix)) {String suffix = s.substring (prefix.length ()); Unmatch.contains (suffix)) {if (wordbreak (suffix, dict, unmatch)) return true;elseunmatch.add (suffix);}} return false;}
Java for Leetcode 139 Word break