Wednesday, January 28, 2015

word break -- Leetcode

Question:

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

Answer:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
      vector<bool> flag(s.length() + 1);
      flag[0] = true;
     
      for (int i = 0; i < s.length(); i++) {                         //s[0]-s[n-1]
         for (int j =i; j >=0; j--) {
            if (flag[j] && dict.find(s.substr(j, i-j+1)) != dict.end()) {                              //flag[j]->s[j-1]
                flag[i+1] = true;
                break;
            }
         }
      }
      return flag[s.length()];
   }
};

No comments:

Post a Comment