/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串一维数组 * @return int* returnSize 返回数组行数 */ #include <stdlib.h> #include <string.h> #define isValid(a) (a >= 0 && a <= 255) // bool isValid(int a) { // if(a >= 0 && a <= 255) return true; // return false; // } char** restoreIpAddresses(char* s, int* returnSize ) { // write code here int len = strlen(s); if(len < 4) return NULL; int dotP1, dotP2, dotP3; int i1 = 0,i2 = 0,i3 = 0,i4 = 0; *returnSize = 0; char** result = (char**)malloc(sizeof(char*)); for(dotP1 = 1; dotP1 < 4; dotP1++) { char temp1[4]; strncpy(temp1, s, dotP1); temp1[dotP1] = '\0'; // printf("strncpy(temp, s, dotP1);的结果是%s\n", temp1); i1 = atoi(temp1); if(!isValid(i1)) continue; if(dotP1 > 1 && temp1[0] == '0' && temp1[1]) continue; for(dotP2 = dotP1 + 1; dotP2 < dotP1 + 4; dotP2++) { char temp2[4]; strncpy(temp2, s + dotP1, dotP2 - dotP1); temp2[dotP2 - dotP1] = '\0'; i2 = atoi(temp2); if(!isValid(i2)) continue; if(dotP2 - dotP1 > 1 && temp2[0] == '0' && temp2[1]) continue; for(dotP3 = dotP2 + 1; dotP3 < dotP2 + 4; dotP3++) { if(len - dotP3 <= 0 || len - dotP3 > 3) continue; char temp3[4]; strncpy(temp3, s + dotP2, dotP3 - dotP2); temp3[dotP3 - dotP2] = '\0'; i3 = atoi(temp3); if(!isValid(i3)) continue; if(dotP3 - dotP2 > 1 && temp3[0] == '0' && temp3[1]) continue; char temp4[4]; strncpy(temp4, s + dotP3, len - dotP3); temp4[len - dotP3] = '\0'; i4 = atoi(temp4); if(!isValid(i4)) continue; if(len - dotP3 > 1 && temp4[0] == '0' && temp4[1]) continue; // printf("%d.%d.%d.%d\n",i1,i2,i3,i4); result[(*returnSize)] = (char*)malloc(sizeof(char) * (len + 3)); if(result[(*returnSize)] == NULL) { for(int i = 0; i < *returnSize; i++) { free(result[i]); } free(result); return NULL; } sprintf(result[(*returnSize)], "%s.%s.%s.%s", temp1, temp2, temp3, temp4); (*returnSize)++; char** new_result = (char**)realloc(result, sizeof(char*) * ((*returnSize) + 1)); if(new_result == NULL) { for(int i = 0; i < *returnSize; i++) { free(result[i]); } free(result); return NULL; } result = new_result; } } } return result; }