1. 程式人生 > >Word Break && Word Break II

Word Break && Word Break II

leetcode上面的兩道動態規劃題。
題目1 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”
給定一個字串s和一個單詞字典,確定是否可以將s分割為空間分隔的
一個或多個字典單詞的序列。

思路:
用f[i]表示0-i可否被目錄字典分割。
f[i] =( f[j] &&( j-i的子串在目錄中)) : 如果f[j]也就是(0-j位置的子串)可被分割且(j到i的子串在目錄中)說明f[j]是可分割的。
n是字串的長度,如果f[n] = true說明字串可以被目錄字典分割。
unordered_set是雜湊的結構。

/*判斷字串是否被字元典可分*/
bool wordBreak(string s, unordered_set<string> &dict)
{
    if (dict.size() == 0 || s.size() == 0)
        return
false; vector<bool> f(s.size()+1, false); //長度有size元素有+1個隔板 f[0] = true; //f[i]表示[0-i]可否被分詞 for (int i = 1; i <=s.size(); ++i) //判斷f[i] { for (int j = i - 1; j >= 0; --j) //f[i] = f[j] && (i-j)是子串 { cout<<s.substr(j, i-j).c_str()<<endl; if
(f[j] && (dict.find(s.substr(j, i-j)) != dict.end())) { f[i] = true; break; } } } return f[s.size()]; }

題目二 Word Break II

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

給定一個字串s和一個單詞字典,在s中新增空格來構造每個單詞的句子
,每個單詞是一個有效的字典單詞。返回所有這些可能的句子。
思路:
增加一個dp[i][j]表示0-i的子串可被劃分,從j處劃分。
auto變數會根據後面的賦值改變自己的屬性。crbegin()中c代表常量,r代表翻轉。


#include <iostream>
using namespace std;
#include <unordered_set>

void getpath(string& s, vector< vector<bool>>& dp, vector<string> &path,
    int len, int cur);
/*判斷字串是否被字元典可分*/
void wordBreak(string s, unordered_set<string> &dict)
{
    if (dict.size() == 0 || s.size() == 0)
        return ;
    vector<bool> f(s.size() + 1, false);
    //長度有size元素有+1個隔板
    f[0] = true;
    //f[i]表示[0-i]可否被分詞
    int len = s.size();
    vector<vector<bool> > dp(len + 1, vector<bool>(len + 1,false));
    for (int i = 1; i <= len; ++i) //判斷f[i]
    {
        for (int j = i - 1; j >= 0; --j) //f[i] = f[j] && (i-j)是子串
        {
            if (f[j] && (dict.find(s.substr(j, i - j)) != dict.end()))
            {
                f[i] = true;
                dp[i][j] = true;
                //[j,i]可劃分
            }
        }
    }
    vector<string>  path;
    getpath(s, dp, path, len, len);
}

void getpath(string& s, vector< vector<bool>>& dp, vector<string> &path,
    int len, int cur)
{
    if (cur == 0)
    {
        string ret;
        for (auto it = path.crbegin(); it != path.crend(); ++it)
        {
            ret += *it;
            ret += " ";
        }
        ret.erase(ret.end()-1);
        //刪除結尾多餘的空格符
        cout<<ret.c_str()<<endl;
    }
    for (int i = 0; i <= len; ++i)
    {
        if (dp[cur][i])
        {
            path.push_back(s.substr(i,cur-i));
            getpath(s, dp, path, len, i);
            path.pop_back();
        }
    }
}

int main()
{
    string str = "catsanddog";
    unordered_set<string> s;
    s.insert("cats");
    s.insert("cat");
    s.insert("dog");
    s.insert("sand");
    s.insert("and");
    wordBreak(str, s);
    return 0;
}

這裡寫圖片描述