/**
* Note: The returned array must be malloced, assume caller calls free().
*/
//保存结果
char **result;
int resultSize;
//一共3个点,记录应加入点的位置
int point[3];
//判断是否有效
int isLegal(char* s, int start, int end){
if(start > end)
return 0;
// 0开头的数字不合法
if (s[start] == '0' && start != end){
return false;
}
int num = 0;
for (int i = start; i <= end;i++){
// 遇到非数字字符,非法
if (s[i] > '9' || s[i] < '0'){
return false;
}
num = num * 10 + (s[i] - '0');//字符转换为整型
// 如果大于255,非法
if (num > 255){
return false;
}
}
return true;
}
//回溯算法
void backtracking(char *s,int start,int point_num){
if(point_num == 3){
//判断最后一段字符串是否合法
if(isLegal(s,start,strlen(s) - 1)){
char *temp = (char*)malloc(sizeof(char) * strlen(s) + 4);
int count = 0,countPoint = 0;
for(int i = 0;i < strlen(s);i++){
temp[count++] = s[i];
if(countPoint < 3 && i == point[countPoint]){
temp[count++] = '.';
countPoint++;
}
}
temp[count] = 0;
result = (char**)realloc(result, sizeof(char*) * (resultSize + 1));
result[resultSize++] = temp;
}
return;
}
//回溯
for(int i = start;i < strlen(s);i++){
if(isLegal(s,start,i)){
point[point_num] = i;//记录放入'.'的位置
backtracking(s,i + 1,point_num + 1);//递归
}
else break;
}
}
char ** restoreIpAddresses(char * s, int* returnSize){
//初始化
result = (char**)malloc(0);
resultSize = 0;
//回溯
backtracking(s, 0, 0);
//返回
*returnSize = resultSize;
return result;
}