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"
.
//使用DP算法!
//注:f(i) = f(j) && find(s.substr(j , i-j)); // f(i)表示s[0..i]可以分词! ---理解即可 一个for 针对i,一个针对j!!
class Solution {
public:
//注:f(i) = f(j) && find(s.substr(j , i-j)); // f(i)表示s[0..i]可以分词!
bool wordBreak(string s, unordered_set<string> &dict) {
int length = s.size();
bool table[length+1];
if(s.empty() || dict.empty())return false;
memset(table,false,sizeof(bool)*(length+1));
table[0] = true;
for(int i = 1; i <= length ; i++)
{
for(int j = 0; j < i; j++)
{
//substr(j , i-j) 此处的j为长度的意思,而下标从0开始,故而不用加1!
if(table[j] && dict.find(s.substr(j , i-j)) != dict.end())
{
table[i] = true ;
}
}
}
return table[length];
}
};
增加输出最多可以划分的个数,时间复杂度O(N^2*m^2*size),也可采取划分,再在trie树中找,时间复杂度O(N^2*m+size*m)//查找速度快!(在搜索中trie树。)
#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <string>
using namespace std;
//注:f(i) = f(j) && find(s.substr(j , i-j)); // f(i)表示s[0..i]可以分词!
int wordBreak(string s, vector<string> &dict) {
int length = s.size();
int *table = new int[length+1];
if(s.empty() || dict.empty())return false;
memset(table,0,sizeof(int)*(length+1));
table[0] = 1;
for(int i = 1; i <= length ; i++)
{
for(int j = 0; j < i; j++)
{
//substr(j , i-j) 此处的j为长度的意思,而下标从0开始,故而不用加1!
if(table[j]>0 && find(dict.begin(),dict.end(),s.substr(j , i-j)) != dict.end())
{
table[i] = table[j]+1;
}
}
}
return table[length] > 1?table[length]-1:0;//一开始多加了1
}
int main()
{
string str[8] = {"a", "an","ave","na","ve","bar", "nave", "on"};
vector<string> dict(str,str+8);
string my_str("anavebaron");
int res;
if(res = wordBreak(my_str,dict))
cout<<"find:"<<res<<endl;
else
cout<<" not find"<<endl;
return 0;
}