Leetcode -- Word Break

来源:互联网 发布:优化驱动器有什么用 编辑:程序博客网 时间:2024/06/03 20: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".

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


0 0
原创粉丝点击