您的位置:首页 > 其它

leetcode笔记:Word Break

2016-01-25 23:48 351 查看
一. 题目描述

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从开始到结尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程。对于下标
i
所对应字符的匹配状态
flag[i]
,如果dict有字符串可以匹配,这取决于之前某个字符
j
的状态出现匹配,从数组s的
j + 1
i
下标之间的字符也能从dict中找到匹配的字符串:

flag[i] = any(flag[j] && (s[j + 1, i] ∈ dict))


三. 示例代码

[code]class Solution
{
public:
    bool wordBreak(string s, unordered_set<string> &dict) 
    {
        vector<bool> wordFlag(s.size() + 1, false); // 动态规划
        wordFlag[0] = true;
        for (int i = 1; i < s.size() + 1; ++i)
        {
            for (int j = i - 1; j >= 0; --j)
            {
                if (wordFlag[j] && dict.find(s.substr(j, i - j)) != dict.end())
                {
                    wordFlag[i] = true;
                    break;
                }
            }
        }
        return wordFlag[s.size()];
    }
};


四. 小结

动态规划对于解决一些字符串的问题也是有效且容易实现的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: