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

LeetCode 139. Word Break

时间:2016-07-03 21:21:01      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

Thought:

for each position, traverse whether it is end with word in wordDict, if is ,and check position[i - len] is true. then position[i] = true

the result depend on position[s.length]

 

Code C++:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        if (s.length() <= 0 || wordDict.size() <= 0) {
            return false;
        }
        
        vector<int> check(s.length() + 1, 0);
        check[0] = 1;
        
        for (int i  = 1; i <= s.length(); i++) {
            for (const string& word : wordDict) {
                int len = word.length();
                if (i - len >= 0 && s.substr(i-len,len) == word && check[i - len] == 1) {
                    check[i] = 1;
                }
            }
        }
        return check[s.length()] == 1;
    }
};

 

LeetCode 139. Word Break

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5638614.html

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