Word Break
第一个问题,递归的方案。time limitted
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict)
{
int len = s.length();
bool *vec =new bool[len];
for(int i = 0;i<len;i++){
vec[i] = false;
}
word(vec,s,0,dict);
bool ret = vec[len-1];
delete vec;
return ret;
}
void word(bool vec[],string s,int start,unordered_set<string> &dict){
if(vec[s.length()-1]){
return;
}
if(start>=s.length()){
vec[s.length()-1] = true;
return;
}
for(int i = start;i<s.length();i++){
if(dict.count(s.substr(start,i-start+1))){
vec[i] = true;
word(vec,s,i+1,dict);
if(vec[s.length()-1]){
break;
}
}
}
}
};
动态规划的方法,通过!
bool wordBreak(string s, unordered_set<string> &dict)
{
int len = s.length();
bool *vec =new bool[len+1];
for(int i = 0;i<=len;i++){
vec[i] = false;
}
vec[0]= true;
for(int i=1;i<=len;i++){
int len1 = i;
for(unordered_set<string>::iterator iter = dict.begin();iter!=dict.end();iter++){
int len2 = iter->size();
if(len1>=len2&&!vec[i]){
if(vec[len1-len2]&&s.substr(len1-len2,len2)==*iter){
vec[i] = true;
break;
}
}
}
}
bool ret = vec[len];
delete vec;
return ret;
}
Word Break II
DP的方法,用一个数组记录,i,j之间的string是否是字符串,然后用一个递归将字符串打印出来,但是超时了。DP还是没学到家。。。
class Solution {
private:
int min;
int max;
vector<string> vec;
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vec.clear();
int len = s.length();
min = len;
max = 0;
bool **P = new bool*[len];
int i,j;
for(i = 0;i<len;i++){
P[i] = new bool[len];
for(j= 0;j<len;j++){
P[i][j]=false;
}
}
unordered_set<string>::iterator iter = dict.begin();
while(iter != dict.end()){
if(iter->size()>max){
max = iter->size();
}
if(iter->size()<min){
min = iter->size();
}
for(i = 0;i<len;){
int pos = s.find(*iter,i);
if(pos!=s.npos){
P[pos][pos+iter->size()-1] = true;
i++;
}
else{
break;
}
}
iter++;
}
string temp = "";
Insert(s,temp,0,P,0,0);
//删除自定义空间
for(i = 0;i<len;i++){
delete P[i];
}
delete P;
return vec;
}
void Insert(string s,string temp,int start,bool **P,int i,int j){
if(j>0){
if(i!=0){
temp.append(" ");
}
temp.append(s.substr(i,j));
}
if(start>=s.size()){
if(!temp.empty()){
vec.push_back(temp);
}
return;
}
for(int i = start;i<start+max&&i<s.size();i++){
if(P[start][i]){
Insert(s,temp,i+1,P,start,i-start+1);
}
}
}
};