码迷,mamicode.com
首页 > 其他好文 > 详细

139. Word Break (String; DP)

时间:2015-10-28 20:59:33      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

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".

思路:用所求值“——是否可以被分段,作为状态;string的每个字符为一个阶段。

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        vector<bool> flag(s.length()+1, false); //indicate if until this position, words can be found in dictionary
        flag[0]=true;
        string str;
        
        for (int i = 0; i < s.length(); i++)
        {
            if(!flag[i]) continue;
            for(int l = 1; l <= s.length()-i;l++)
            {
                str = s.substr(i,l);
                if(dict.find(str)!=dict.end())
                {
                    flag[i+l] = true;
                }
            }
        }
        return flag[s.length()];
    }
};

 

139. Word Break (String; DP)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4918289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!