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

 

dp做法

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        int dp[s.size()]={0};
        //dp[i]代表 前i个字符 组成的字符串能不能在字典里面找到
        dp[0]=1;
        for(int i=1;i<=s.size();i++){
            int j=i;
            while(j>=0&&dp[i]==0){
                if(dp[j]==1&&wordDict.count(s.substr(j, i - j)))dp[i]=1;
                else j--;
            }
        }
        return dp[s.size()];
    }
};

 

posted on 2016-04-05 18:25  Beserious  阅读(240)  评论(0编辑  收藏  举报