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

[LeetCode] 139 Word Break

时间:2017-10-16 22:01:27      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:into   dict   problems   sep   cat   begin   ret   log   ted   

原题地址:

https://leetcode.com/problems/word-break/description/

 

题目:

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

 

解法:

这道题目利用动态规划做出来,不得不说想法是很巧妙的,我也是参考了网上的代码才AC了。因此,先放代码,等我完全弄懂再补充吧:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        if(s == "" || s.size() == 0) {
            return true; 
        }
        unordered_map<int, bool> res;
        for (int i = 0; i <= s.size(); i++) {
            res[i] = false;
        }
        res[0] = true;
        for (int i = 0; i < s.size(); i++) {
            string str = s.substr(0, i + 1);
            for (int j = 0; j <= i; j++) {
                if (res[j] && find(wordDict.begin(), wordDict.end(), str) != wordDict.end()) {
                    res[i + 1] = true;
                    break;
                }
                str = str.substr(1, str.size() - 1);
            }
        }
        return res[s.size()];
    }
};

 

[LeetCode] 139 Word Break

标签:into   dict   problems   sep   cat   begin   ret   log   ted   

原文地址:http://www.cnblogs.com/fengziwei/p/7678271.html

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