[leetcode 139]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".

对从第一个字符到最后一个字符进行切分,新建一个数组备忘

count[i]=1表示字符串s从第一个字符到弟i个字符可以由字典组成

遍历字符串不断切分,返回count[s.size()]

AC代码

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
    int len=s.size();
    int sum=wordDict.size();
    if(len==0&&sum==0)
        return true;
    else if(len==0||sum==0)
        return false;
    int count[len+1];
    memset(count,0,sizeof(count));
    count[0]=1;
    string temp="";
    for(int i=1;i<=len;++i)
    {
        for(int j=i-1;j>=0;--j)
        {
            temp=s.substr(j,i-j);
            if(count[j]&&wordDict.find(temp)!=wordDict.end())
            {
                count[i]=1;
                break;
            }
        }
    }
    return count[len];
    }
};
其他Leetcode题目AC代码:https://github.com/PoughER/leetcode


你可能感兴趣的:(LeetCode,dp,break,word,139)