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

Subscribe to see which companies asked this question


class Solution {
public:
    bool wordBreak(string s, unordered_set& wordDict) {
        int len = s.length();

		if(len == 0) return true;
        if(wordDict.empty()) return false;
        
		vector dp(len, 0);

		for(int i = 0; i < len; i++) {
			for(int j = i; j >= 0; j--) {
			    string str = s.substr(j, i-j+1);
			    
			    if(wordDict.find(str)!=wordDict.end()) {
			        if(j <= 0) dp[i] = 1;
			        else if(dp[j-1] == 1) {
			            dp[i] = 1;
			            break;
			        }
			    }
			}
		}

		return dp[len-1];
    }
};




你可能感兴趣的:(Leetcode)