【LeetCode】Word Break

来源:互联网 发布:linux创建文本文件命令 编辑:程序博客网 时间:2024/05/30 04:42

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

分析:采用动态规划的方法,将源字符串从头到尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程,设状态为 f (i),表示 s[i,j] 是否可以分词,则状态转移方程为 f(i) =any_of(f(j) && s[j+ 1, i]∈ dict),0 ≤ j < i 

class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {        vector<bool> f(s.size()+1, false);        f[0] = true; // 空字符串        for(int i=1; i<=s.size(); ++i){            for(int j=i-1; j>=0; --j){                if(f[j] && dict.find(s.substr(j, i-j)) != dict.end()){                    f[i] = true;                    break;                }            }        }        return f[s.size()];    }};


0 0
原创粉丝点击