leetcode——139——Word Break

来源:互联网 发布:自贡广电网络 编辑:程序博客网 时间:2024/06/01 10:53
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".

这题可以用DFS做,但是更好的方法是使用DP,这种类型的DP感觉还是接触的稍微有些少。

题目中只要求源串分出来的词只要都在字典里就好,所以我们可以用dp[i] 表示源串的前i个字符可以满足分割,那么 dp[ j ] 满足分割的条件是存在k (0<=k<=j)使得 dp [k] && s[k+1,j]在字典里即可。注意下标问题,dp[i]是指前i个字符,对应的字母是s[i-1].


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




0 0