LeetCode OJ 之 Word Break (断词)

来源:互联网 发布:linux打包命令 tar 编辑:程序博客网 时间:2024/06/15 01:22

题目:

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 ),表示前i个字符s[0,i-1] 是否可以分词,则状态转移方程为
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)    {        //f ( i ) = any_of (f (j )&&s [j + 1, i ] ∈ dict ), 0 ≤ j < i        vector<bool> f(s.size()+1,false);        f[0] = true;        for(int i = 1 ; i <= s.size() ; i++)        {            for(int j = 0 ; j < i ; j++)            {                f[i] = f[j] && (dict.find(s.substr(j,i-j)) != dict.end());                if(f[i])                    break;            }        }        return f[s.size()];    }};


0 0
原创粉丝点击