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

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        if(s.empty())return true;
        if(dict.empty()) return s.empty();
        vector<bool> dp(1+s.length(),false);
        dp[0]=true;
        for(int i=1;i<=s.length();i++)
        {
            for(int j=i-1;j>=0;j--)
            {
                dp[i]=dp[j]&&(dict.count(s.substr(j,i-j)));
                if(dp[i])break;
            }
        }
        return dp[s.length()];
    }
};

 

posted @ 2015-02-09 12:50  Vae永Silence  阅读(142)  评论(0编辑  收藏  举报