[leetcode]Word Break

来源:互联网 发布:开发php扩展 编辑:程序博客网 时间:2024/04/29 10:14

class Solution {

public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int n = (int)s.size();
        vector<bool> dp(n + 1, false);
        dp[0] = true;
        for (int i = 0; i < n; i++) {
            if (dp[i]) {
                for (int len = 1; i + len - 1 < n; len++) {
                    if (dict.count(s.substr(i, len)) > 0)
                        dp[i + len] = true;
                }
            }
        }
        return dp[n];
    }
};