我正在处理一个 DP 问题,其中删除了空格的字符串,我需要实现自下而上和记忆化版本以将字符串拆分为单个英文单词。然而,我得到了自下而上的版本,然而,记忆似乎有点复杂。
/* Split a string into individual english words
* @String str the str to be splitted
* @Return a sequence of words separated by space if successful,
null otherwise
*/
public static String buttom_up_split(String str){
int len = str.length();
int[] S = new int[len+1];
/*Stores all the valid strings*/
String[] result = new String[len+1];
/*Initialize the array*/
for(int i=0; i <= len; i++){
S[i] = -1;
}
S[0] =0;
for(int i=0; i < len; i++){
if(S[i] != -1){
for(int j= i+1; j <= len; j++){
String sub = str.substring(i, j);
int k = j;
if(isValidEnglishWord(sub)){
S[k] = 1; //set true indicates a valid split
/*Add space between words*/
if(result[i] != null){
/*Add the substring to the existing words*/
result[i+ sub.length()] = result[i] + " " + sub;
}
else{
/*The first word*/
result[i+ sub.length()] = sub;
}
}
}
}
}
return result[len]; //return the last element of the array
}
我真的很困惑如何将这个buttom_up_version转换为memoized版本,希望有人能帮忙..