Java for Leetcode-Word break II

Source: Internet
Author: User

Given A string s and a Dictionary of words dict, add spaces in s to construct a sentence where Each of the word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog" ,
dict = ["cat", "cats", "and", "sand", "dog"] .

A solution is ["cats and dog", "cat sand dog"] .

Problem Solving Ideas:

Refer to the method of thinking two of the solution, modify the code, let it show the path, Java implementation is as follows:

static public list<string> Wordbreak (String s, set<string> worddict) {list<string> List = new ArrayList <String> ();d FS (list, S, Worddict, New Hashset<string> (), New arraylist<string> ()); return list;} Static public boolean DFS (list<string> List, String S, set<string> dict,set<string> Unmatch, list< String> alist) {boolean ismatch=false;for (String prefix:dict) {if (s.equals (prefix)) {alist.add (prefix)}; StringBuilder sb = new StringBuilder (); for (String str:alist) {sb.append (str); Sb.append ("");} List.add (sb.substring (0, Sb.length ()-1)); Alist.remove (Alist.size ()-1); ismatch=true;continue;} else if (s.startswith (prefix)) {String suffix = s.substring (prefix.length ()); if (!unmatch.contains (suffix)) {Alist.add (prefix), if (!dfs (list, suffix, dict, Unmatch, alist)) unmatch.add (suffix); else Ismatch=true;alist.remove (Alist.size ( )-1);}}} return isMatch;}

Java for Leetcode-Word break II

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.