Java for Leetcode 139 Word break

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.