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

139. Word Break

时间:2017-07-26 01:43:53      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:can   solution   sub   cti   space   定义   word   term   rds   

#139. Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

##分析##
定义 d[i]表示 0~i子串是否能通过dict中元素表示    
如果存在{str(j,i)∈ dict | j<i } 则d[i]=true    

##代码##
    
    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) 
        {
            unordered_set<string> dict;
            for(int i = 0; i < wordDict.size(); i++)
            {
                dict.insert(wordDict[i]);
            }
            
            size_t len = s.size();
            vector<int> d(len+1, false);
            d[0] = true;
            for(int i = 1; i < len+1; i++)
                for(int j=i-1;j>=0;j--)
                {
                    if(d[j] && dict.find(s.substr(j,i-j)) != dict.end())
                    {
                        d[i] = true;
                        break;
                    }
                }
            return d[len];
        }
    };
    

139. Word Break

标签:can   solution   sub   cti   space   定义   word   term   rds   

原文地址:http://www.cnblogs.com/strom109212/p/7237149.html

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