[LeetCode]Word Break

Question:

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

分析:一开始先用的递归算法,但是系统报错:

Submission Result: Time Limit Exceeded

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

递归代码如下:

class Solution {
public:
    bool wordBreak(string s, unordered_set &dict) {
        int len = s.size();
        int start = 0;
        bool contain = false;
        if (s.size() < 1) return true;
        for (int j = 1; j <= len; j++)
        {
            string str = s.substr(start, j - start);
            if (dict.count(str) == 1)
            {
                if (str.size() == s.size()) return true;
                else contain = wordBreak(s.substr(j), dict);
            }
            if (contain) return true;
        }
        return false;
    }
};


然后开始尝试用动态规划来实现,利用一个一维bool数组记录子串是否可以有效word break,这样减少了重复判断子串的次数,效率明显提高。 代码如下: 

class Solution {
public:
    bool wordBreak(string s, unordered_set &dict) {
        if(s.empty()||dict.empty()) return false;
        vector f(s.size() + 1, false);
        f[0] = true;
        for (int i = 1; i <= s.size(); i++)
        {
            for (int j = 0; j < i; j++)
            {
                if (f[j] && dict.count(s.substr(j, i-j)))
                {
                    f[i] = true;
                    break;
                }
            }
        }
        return f[s.size()];
    }
};


你可能感兴趣的:(算法C++描述,LeetCode,Excercise,C++,语言,word,break)