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;
    }
};

 

posted on 2016-07-03 19:17  gavinXing  阅读(156)  评论(0编辑  收藏  举报