Word Break II

来源:互联网 发布:淘宝同行竞争插件 编辑:程序博客网 时间:2024/05/22 17:22

 Givena string s and a dictionary of words dict, add spaces in s to construct a sentence where each wordis a valid dictionary word.

Return all such possible sentences.

For example, given
s 
"catsanddog",
dict 
["cat","cats", "and", "sand", "dog"].

A solution is ["cats anddog", "cat sand dog"].

思路:这题和上题的解法基本一致,不同的就是需要存储每个位置上到结尾包含的所有单词。

class Solution {public:    vector<string> wordBreak(string s, unordered_set<string> &dict) {        int size = s.size();          vector<vector<string>> result(size+1, vector<string>());          for (int i = size - 1; i >= 0; --i) {              for (int j = i; j < size; ++j) {                  string word = s.substr(i, j-i+1);                  if (dict.find(word) != dict.end()) {                      if (j + 1 >= size) {                          result[i].push_back(word);                      }                      else {                          for (int k = 0; k < result[j+1].size(); ++k) {                              result[i].push_back(word + " " + result[j+1][k]);  //result[i]上存储以i开头的单词                        }                      }                  }              }          }                 return result[0];              }};


0 0
原创粉丝点击