Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa

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

1.递归

#include <iostream>
#include <set>
#include <string>
using namespace std;
class Solution {
public:
    bool wordBreak(string s,set<string> &dict) {
      if(s.length() == 0){
        return true;
      }
      set<string>::iterator it = dict.begin();
      for (;it != dict.end(); ++it) {
        string elem = *it;
        if(dict.find(s.substr(0,elem.length())) != dict.end()) {
           if(elem.length() == s.length()) {
              return true;
           }
           if (!wordBreak(s.substr(elem.length()),dict)) {
             continue;
           }
          else{
            return true;
          }
        }
      }
      return false;
    }
};

2.动态规划

你可能感兴趣的:(数据结构,算法)