4ms Easy C++ Solution with Explanations


  • 1

    Well, it seems that many people meet the TLE problem. Well, I use a simple trick in my code to aoivd TLE. That is, each time before I try to break s, I call isBreakable (justwordBreak from Word Break) to see whether it is breakable. If it is not breakable, then we need not move on. Otherwise, we break it using backtracking.

    The idea of backtracking is also typical. Start from index 0 of s, each time we see a word that is in wordDict, add it to a temporary string sentence. When we reach the end of the s, add sentence to sentences. Then we need to recover sentence back to its original status before word was added. So I simply record a temporary string temp each time before I add word to sentence and use it to recover the status.

    The code is as follows. I hope it to be self-explanatory enough.

    class Solution { 
    public:
        bool isWordBreak(string& s, unordered_set<string>& wordDict) {
            vector<bool> dp(s.length() + 1, false);
            dp[0] = true;
            int minlen = INT_MAX; 
            int maxlen = INT_MIN;
            for (string word : wordDict) {
                minlen = min(minlen, (int)word.length());
                maxlen = max(maxlen, (int)word.length()); 
            }
            for (int i = 1; i <= s.length(); i++) {
                for (int j = i - minlen; j >= max(0, i - maxlen); j--) {
                    if (dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) {
                        dp[i] = true;
                        break;
                    }
                } 
            }
            return dp[s.length()];
        }
        void breakWords(string s, int idx, unordered_set<string>& wordDict, string& sol, vector<string>& res) {
            if (idx == s.length()) { 
                sol.resize(sol.length() - 1);
                res.push_back(sol);
                return;
            }
            for (int i = idx; i < s.length(); i++) {
                string word = s.substr(idx, i - idx + 1);
                if (wordDict.find(word) != wordDict.end()) {
                    string tmp = sol;
                    sol += word + " ";
                    breakWords(s, i + 1, wordDict, sol, res);
                    sol = tmp;
                }
            }
        }
        vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
            string sol;
            vector<string> res;
            if (!isWordBreak(s, wordDict)) return res;
            breakWords(s, 0, wordDict, sol, res); 
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.