[Leetcode]Word Break & Word Break II

来源:互联网 发布:android记账软件源码 编辑:程序博客网 时间:2024/06/04 19:40

Word Break is a problem that gives you a string and a dict of word, you have to indicate that if the string is a combination of the given words.


It is quite simple dp problem, the solution is like this.


dp[0] = 1;if dp[i]:   dp[j] = 1 if str[i...j] in dict else 0

And the answer is true if dp[strlen(str)] is true, otherwise, it will return false.


class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {        memset(dp, 0, sizeof(dp));        dp[0] = 1;        int len = s.length();                for (int i = 0; i <= len; i++) {            if (dp[i]) {                string tmp;                for (int j = i + 1; j <= len; j++) {                    tmp += s[j - 1];                    if (dict.find(tmp) != dict.end()) {                        dp[j] = 1;                    }                }            }        }        return dp[len];    }        static const int SIZE = 1024;    int dp[SIZE];};


Word Break II is an update version of previous problem. It needs you to point out how to construct the very string using given words.

So, we use an array of vector to store which words are used in this position.

At last, we dfs from right to left and make up the strings for the final answer.


class Solution {public:    vector<string> wordBreak(string s, unordered_set<string> &dict) {        for (int i = 0; i < SIZE; i++) {            dp[i].clear();        }        itos.clear();        stoi.clear();        ans.clear();        int idx = 0;        for (auto iter = dict.begin(); iter != dict.end(); ++iter) {            itos.push_back(*iter);            stoi[*iter] = idx;            idx++;        }        int len = s.length();                dp[0].push_back(-1);        for (int i = 0; i <= len; i++) {            if (!dp[i].empty()) {                string ss;                for (int j = i + 1; j <= len; j++) {                    ss += s[j - 1];                    if (dict.find(ss) != dict.end()) {                        idx = stoi[ss];                        dp[j].push_back(idx);                    }                }            }        }        string tmp;        dfs(len, tmp);        return ans;    }        void dfs(int pos, string& tmp) {        if (pos == 0) {            ans.push_back(tmp);            return;        }        for (auto iter = dp[pos].begin(); iter != dp[pos].end(); ++iter) {            string next;            int now = *iter;            if (tmp.empty()) {                next = itos[now];            } else {                next = itos[now] + " " + tmp;            }            dfs(pos - itos[now].size(), next);        }    }        static const int SIZE = 1024;    vector<string> ans;    vector<int> dp[SIZE];    vector<string> itos;    map<string, int> stoi;};



0 0
原创粉丝点击