lintcode:Word Break

来源:互联网 发布:网络规划设计师视频 编辑:程序博客网 时间:2024/05/21 00:18

Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

设res[i]表示s的前i个数字母能否分拆后在dict中找到。

如果这里写图片描述,则res[i]=true;

class Solution {public:    /**     * @param s: A string s     * @param dict: A dictionary of words dict     */    bool wordBreak(string s, unordered_set<string> &dict) {        // write your code here        int len=s.size();        if(len==0){            return true;        }        if(dict.size()==0){            return false;        }        int maxLen=0;        for(string str:dict){            if(str.size()>maxLen){                maxLen=str.size();            }        }        vector<bool> res(len+1,false);        res[0]=true;        for(int i=1;i<=len;i++){            for(int j=i-1;j>=0;j--){                if(i-j>maxLen){                    break;                }                bool flag=res[j]&& dict.find(s.substr(j,i-j))!=dict.end();                if(flag){                    res[i]=true;                    break;                }            }        }        return res[len];    }};
0 0
原创粉丝点击