leetcode-Word Break

来源:互联网 发布:手游网游 知乎 编辑:程序博客网 时间:2024/05/29 04:31

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 findWord(vector<vector<bool>> &b, int l, int n, vector<bool> &suffix)    {        if(l == n)        {            return true;        }                if((l != 0)&&(!suffix[l-1]))return false;                for(int i = 0; i < n-l; i++)        {            if(b[i][l])            {                if(findWord(b,l+i+1,n,suffix))return true;                else suffix[l+i] = false;            }        }        return false;    }        bool wordBreak(string s, unordered_set<string> &dict) {        vector<vector<string>>v;        vector<vector<bool>>pal;                vector<vector<string>>ret;        int n = s.length();        if(n==0)return true;        for(int i = 1; i <= n; i++)        {            vector<bool>b;            for(int j = 0; j <= n-i; j++)            {                string s1;                s1.assign(s,j,i);                bool t = false;                if(dict.find(s1) != dict.end()) t = true;                b.push_back(t);                            }            pal.push_back(b);        }        vector<bool> suffix;        for(int i = 0; i < n; i++)suffix.push_back(true);        return findWord(pal,0,n,suffix);    }};


0 0
原创粉丝点击