Thursday, September 25, 2014

[Leetcode] Word Break

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

  • If s has only character, s could be break if s[0] is a word.
  • If s has two characters, s could be break if both s[0] and s[1] are the word or s.substr(0,2) is a word.
  • if s has If s has two characters, s could be break if there exist a j (0<=j<i) such that s.substr(0, j) could be break and s.substr(j, i-j+1) is a word. Notice that we only need to know whether  s.substr(0, j) could be break and don't care how it is break.

Let canBreak[i] to indicate whether s.substr(0,i) could be break


    bool wordBreak(string s, unordered_set<string> &dict) {
        //indicate whether the substr(s, 0, i) could be breaked into words
        vector<bool> canBreak(s.size(), false);
        for(int i=0; i<s.size(); i++)
        {
            //either the whole string is a word
            if(dict.find(s.substr(0, i+1)) != dict.end())
                canBreak[i] = true;
            else
            {
                //or substr1 can be breaked and substr2 is a word
                for(int j=0; j<i; j++)
                {
                    if (canBreak[j] && dict.find(s.substr(j+1, i-j)) != dict.end())
                    {
                        canBreak[i] = true;
                        break;
                    }
                }
            }
        }
        
        return canBreak[s.size()-1];
    }

No comments:

Post a Comment