[LeetCode] word break 字符串的划分

Given a string s and a dictionary of words dict, determine if s can 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 as "leet code".

思路:动态规划。申请一个 bool 数组 marks,初始化为false。 

marks[i] = true if 1)  s.substr(0,i) 是字典里的一个单词

                         2)  或者存在一个 j,使得 marks[j]=true 而且 s.substr(j+1, i) 是个字典里的单词。

代码:

    bool wordBreak(string s, unordered_set<string> &dict)
    {
            bool* marks = new bool[ s.length() ];
            memset(marks, 0, s.length() ); //初始化
    
            for(int i=0; i<s.length(); i++)
            {   
                    if( dict.find( s.substr(0, i+1) ) != dict.end() )
                            *(marks+i) = true;
                            
                    if(i>0)
                            for(int j=0; j<i; j++)
                            {   
                                    if( *(marks+j)==true && ( dict.find( s.substr(j+1, i-j) ) != dict.end() ) )
                                    {   
                                            *(marks+i) = true;
                                            break;
                                    }   
                            }   
            }   
            return *(marks+s.length()-1);
    }

----------------------------------------------------------------------

Given a string s and a dictionary of words dict, add spaces in s to 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"].

下面的代码可以输出word break的结果。

    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        
        vector< vector<string> > wordBreaks; //wordBreaks[i] 是s.substr(0,i) 所有可能的break的结果
        
        int len = s.length();
        
        for(int i=0; i<len; i++)
        {
            vector<string> vec;
            wordBreaks.push_back(vec);

            if(dict.find( s.substr( 0, i+1) ) != dict.end())
            {
                string str = s.substr( 0, i+1 );
                wordBreaks[i].push_back(str);
            }
             
            if(i>0)
                for(int j=0; j<i; j++)
                {
                    
                    if( wordBreaks[j].size() > 0 && dict.find( s.substr( j+1, i-j ) ) != dict.end() )
                    {
                        for(int k=0; k<wordBreaks[j].size(); k++)
                        {
                            string str = wordBreaks[j][k];
                            str = str + " " + s.substr( j+1, i-j );
                            wordBreaks[i].push_back(str);   
                        }
                    }
                }
            
        }
        
        
        return wordBreaks[len-1];
    }



你可能感兴趣的:([LeetCode] word break 字符串的划分)