0
点赞
收藏
分享

微信扫一扫

139. Word Break

修炼之士 2023-09-05 阅读 7


non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s

For example, given

s = "leetcode",

dict = ["leet", "code"]."leetcode" can be segmented as "leet code".

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int length = s.length();
        if(wordDict.size() == 0 && length > 0)
            return false;
//        return dfs(s,wordDict,0);
        vector<bool> flag(length + 1,false);
        flag[0] = true;
        for(int i = 1; i <= length; i ++){
            for(int j = i - 1; j >= 0; j --){
                string temp = s.substr(j, i - j);
                if(flag[j] && find(wordDict.begin(),wordDict.end(),temp) != wordDict.end()){
                    flag[i] = true;
                    break;
                }
            }
        }
      return flag[length]; 
    }
    
    bool dfs(string s, vector<string>& wordDict, int index){
        int length = s.length();
        if(index >= length)
            return true;
        string temp;
        for(int i = index; i < length; i ++){
            temp = s.substr(index, i - index + 1);
            if(find(wordDict.begin(),wordDict.end(),temp) != wordDict.end())
                if(dfs(s,wordDict,i + 1))
                    return true;
        }
        return false;
    }
};




举报

相关推荐

0 条评论