Word Break

优化点:

1)第二层for,找到一个true就可以break;

2)第二层for,不用0...i,可以算出wordDict的最长单词长度,节省部分时间;

code


class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        if(s.empty())
        {
            return true;
        }

        int n = s.length();
        vector<bool> dp(n+1, false);
        dp[0] = true;

        for(int i = 1; i<n+1; i++)
        {
            for(int j = 0; j<i; j++)
            {
                if(dp[j] == false)
                {
                    continue;
                }

                string cur = s.substr(j, i-j);

                if(wordDict.find(cur) == wordDict.end())
                {
                    continue;
                }

                dp[i] = true;
                break;
            }
        }

        return dp[n];
    }
};

results matching ""

    No results matching ""