13.12—动态规划—Word Break

来源:互联网 发布:tplink访客网络是什么 编辑:程序博客网 时间:2024/05/19 13:57
描述
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".

#include<iostream>#include<set>#include<vector>#include<string>using namespace std;bool WordBreak(string s, set<string> hashtable)//该题解法有问题!{if (s.size() < 1)return false;int len = s.size();vector<bool> vec(len + 1, false);vec[0] = true;for (int i =1 ; i <=len; i++){for (int j = i; j >= 1; j--){if (vec[j-1]){if ((hashtable.find(s.substr(j - 1, i - j + 1)) != hashtable.end()))vec[i] = true;break;}}}return vec[len];}int main(){string s = "abcdeefg";set<string> hashtable;hashtable.insert("ab");hashtable.insert("cde");hashtable.insert("ee");hashtable.insert("fg");bool flag = WordBreak(s, hashtable);if (flag)cout << s << " contains the dict!" << endl;}

原创粉丝点击