leetcode---word-break---dp

来源:互联网 发布:python assert() 编辑:程序博客网 时间:2024/06/07 03:55

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)     {        int n = s.size();        vector<bool> dp(n+1, false);        dp[0] = true;        for(int i=0; i<n; i++)        {            string subs = s.substr(0, i+1);            for(int j=0; j<=i; j++)            {                if(dp[j] && dict.count(subs))                    dp[i+1] = true;                subs = subs.substr(1, subs.size() - 1);            }        }        return dp[n];    }};