/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
char** path;
int pathTop;
char*** ans;
int ansTop;
int* ansSize;
//判断字符串是否为回文串
bool ispalindrome(char* s,int start,int end){
while(start <= end){
if(s[start++] != s[end--]){
return 0;
}
}
return 1;
}
//切割处理
char* cut(char *s,int start,int end){
//开辟空间
char* tempStr = (char*)malloc(sizeof(char) * (end - start + 2));
int index = 0;
//复制在tempStr
for(int i = start;i <= end;i++){
tempStr[index++] = s[i];
}
tempStr[index] = '\0';
//返回tempStr
return tempStr;
}
//回溯算法
void backtracking(char* s,int sSize,int index){
if(index >= sSize){
//tempPath保存path中的字符串
char** tempPath = (char**)malloc(sizeof(char*) * pathTop);
for(int i = 0; i < pathTop; i++) {
tempPath[i] = path[i];
}
//保存tempPath
ans[ansTop] = tempPath;
ansSize[ansTop++] = pathTop;
return;
}
for(int i = index;i < sSize;i++){
//处理
if(ispalindrome(s,index,i)) {
path[pathTop++] = cut(s,index,i);
}
else{
continue;
}
//递归判断下一层
backtracking(s,sSize,i+1);
//回溯
pathTop--;
}
}
char *** partition(char * s, int* returnSize, int** returnColumnSizes){
//初始化
path = (char**)malloc(sizeof(char*) * strlen(s));
ans = (char***)malloc(sizeof(char**) * 40000);
ansSize = (int*)malloc(sizeof(int) * 40000);
ansTop = pathTop = 0;
//回溯计算
backtracking(s,strlen(s),0);
*returnSize = ansTop;
*returnColumnSizes = (int*)malloc(sizeof(int) * ansTop);
for(int i = 0; i < ansTop; ++i) {
(*returnColumnSizes)[i] = ansSize[i];
}
return ans;
}
LeetCode:131. 分割回文串
最新推荐文章于 2024-07-25 17:54:26 发布