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

粗暴递归,结果超时

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(s == null) return false;
        int start, end;
        start = end = 0;
        int length = s.length();
        while(start < length){
                 if( dict.contains(s.substring(0,start)) && wordBreak(s.substring(start+1),dict) ){
                     return true;
                 }else{
                     start++;
                 }
        }
        return false;
    }
}

 

Submission Result: Time Limit Exceeded ()

Last executed input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]

DP Solution:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<bool> checked(s.length()+1, false);
        checked[0] = true;
        for (int i = 1; i <= s.length(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (checked[j] && dict.find(s.substr(j,i-j)) != dict.end()) {
                    checked[i] = true;
                    break;
                }
            }
        }
        return checked[s.length()];
    }
};

 

posted @ 2014-03-01 16:06  andyqee  阅读(157)  评论(0编辑  收藏  举报