[Leetcode] 140. Word Break II Java

Source: Internet
Author: User

Topic:

Given a non-empty string s and a dictionary worddict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Assume the dictionary does not contain duplicate words.

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"] .

test instructions and analysis: given a string and a dictionary, it is possible to use a dictionary word to divide a string. Using a deep traversal method, each time the string is judged to start with a word in the dictionary, and if it starts, the remaining string is judged, and if the last string length is 0, the words that can split the string are found. This saves the intermediate result with a hashmap, otherwise it will time out.

Code:

classSolution { PublicList<string> Wordbreak (String s, list<string>worddict) {        returnDFS (S, Worddict,NewHashmap<string, linkedlist<string>>()); } List<String> DFS (String s,list<string> worddict,hashmap<string,linkedlist<string>>map) {        if(Map.containskey (s))returnMap.get (s); LinkedList<String> res =NewLinkedlist<>(); if(s.length () = = 0) {Res.add (""); returnRes; }         for(String word:worddict) {if(S.startswith (Word)) {List<String> sublist =DFS (s.substring (Word.length ()), worddict,map);  for(String sub:sublist) {res.add (Word+ (Sub.isempty ()? "":" ")+sub);        }}} map.put (S,res); returnRes; }}

[Leetcode] 140. Word Break II Java

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.