leetcode 139. Word Break(dp,字典匹配)

来源:互联网 发布:windows木马编程 编辑:程序博客网 时间:2024/06/06 14:11

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



分析:

ac代码:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int i,j,L=s.length();
        bool word[L+1];
        for(i=1;i<=L;i++)
        word[i]=false;
        word[0]=true;
        for(i=1;i<=L;i++)
        {
            for(j=i-1;j>=0;j--)
            {
                if(word[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end())
                {
                    word[i]=true;
                    break;
                }
            }
        }
        return word[L];    
    }
};

0 0
原创粉丝点击