LeetCode-Word Break

Source: Internet
Author: User

LeetCode-Word Break

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"leet code".

In this example, we mainly want to see whether the words in a sentence string can be divided into words in the dictionary.

If flag [j] is true, a variable k must exist, which can satisfy the condition that flag [k] is true, and substr (k, j-k) is in the dictionary.

However, in this example, we do not care about the final division method.

 

Class Solution {public: bool wordBreak (string s, unordered_set
 
  
& Dict) {int length = s. size (); vector
  
   
Val (length + 1, false); val [0] = true; // <set int I = 0 according to the length; int j = 0; for (I = 0; I <length; I ++) {if (val [I]) // <the previous length can be decomposed {for (j = 1; (I + j) <= length; j ++) {string tmp = s. substr (I, j); if (dict. count (tmp)> 0) {val [I + j] = true ;}}} return val [length] ;}};
  
 

There is a second example:

 

Word Break II

 

 

Given a stringSAnd a dictionary of wordsDict, Add spaces inSTo construct a sentence where each 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"].

In this example, we need to put the decomposition result in a vector struct.

One method is the DFS method, which has not been studied yet.

The method in the first example is used as a reference here to check whether the partition can be made. If the partition can be made, it is then stored through traversal.

 

class Solution {public:    void breakWord(vector
 
   &res, string &s, unordered_set
  
    &dict, string str, int idx, vector
   
     &dp) {        string substr;        for (int len = 1; idx + len <= s.length(); ++len) {            if (dp[idx + len] && dict.count(s.substr(idx,len)) > 0) {                substr = s.substr(idx, len);                if (idx + len < s.length()) {                    breakWord(res, s, dict, str + substr + " ", idx + len, dp);                } else {                    res.push_back(str + substr);                    return;                }            }        }    }        vector
    
      wordBreak(string s, unordered_set
     
       &dict) {        vector
      
        dp(s.length() + 1, false); dp[0] = true; for (int i = 0; i < s.length(); ++i) { if (dp[i]) { for (int len = 1; i + len <= s.length(); ++len) { if (dict.count(s.substr(i, len)) > 0) { dp[i + len] = true; } } } } vector
       
         res; if (dp[s.length()]) breakWord(res, s, dict, "", 0, dp); return res; }};
       
      
     
    
   
  
 


 

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.