【LeetCode】139. 单词拆分——dp

题目

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。

示例 1:

输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"

解答

参考Code_Gank的博客的思路。
这里我用了一个unordered_set方便快速查找字符串。

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> dict;
        for (int i = 0; i < wordDict.size(); i++)
            dict.insert(wordDict[i]);

        vector<bool> dp(s.length(), false);
        dp[0] = (dict.find(s.substr(0, 1)) == dict.end()) ? false : true;

        for (int i = 1; i < s.length(); i++) {
            int j = 0;
            for (; j <= i; j++) {
                string sub = s.substr(j, i-j+1);
                if (dict.find(sub) != dict.end() && (j == 0 || dp[j-1])) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()-1];
    }
};

你可能感兴趣的:(LeetCode)