|

楼主 |
发表于 2020-4-7 22:06:03
|
显示全部楼层
- int getInt(char *s, int pos, int byteCnt)
- {
- char tmp[4];
- if (byteCnt > 3) {
- return 0;
- }
- memcpy(tmp, &s[pos], byteCnt);
- tmp[byteCnt] = 0;
- return atoi(tmp);
- }
- void step(char* s, int index, int pos, int byteCnt, char **result, int *returnSize, int* tmp)
- {
- int len = strlen(&s[pos]);
- int size = 17;
- if ((len < byteCnt) || (index > 3) || ((len - byteCnt) > ((4 - index - 1) * 3))) {
- return;
- }
- if ((index == 3) && (len != byteCnt)) {
- return;
- }
- if (byteCnt == 3) {
- if ((s[pos] > '2') || ((s[pos] == '2') && (s[pos + 1] > '5')) || ((s[pos] == '2') && (s[pos + 1] == '5') && (s[pos + 2] > '5'))) {
- return;
- }
- }
- if ((s[pos] == '0') && (byteCnt > 1)) {
- return;
- }
- tmp[index] = getInt(s, pos, byteCnt);
- if (index == 3) {
- result[*returnSize] = (char*)malloc(size);
- snprintf(result[*returnSize], size - 1, "%d.%d.%d.%d", tmp[0], tmp[1], tmp[2], tmp[3]);
- result[*returnSize][size - 1] = 0;
- (*returnSize)++;
- } else {
- step(s, index + 1, pos + byteCnt, 1, result, returnSize, tmp);
- step(s, index + 1, pos + byteCnt, 2, result, returnSize, tmp);
- step(s, index + 1, pos + byteCnt, 3, result, returnSize, tmp);
- }
- }
- /**
- * Note: The returned array must be malloced, assume caller calls free().
- */
- char ** restoreIpAddresses(char * s, int* returnSize){
- int resultCnt = 0;
- char **result;
- int tmp[4] = {0, 0, 0, 0};
- if (!s || !s[0] || !returnSize) {
- if (returnSize) {
- *returnSize = 0;
- }
- return NULL;
- }
- result = (char**)malloc(81 * sizeof(char*));
- *returnSize = 0;
-
- step(s, 0, 0, 1, result, returnSize, tmp);
- step(s, 0, 0, 2, result, returnSize, tmp);
- step(s, 0, 0, 3, result, returnSize, tmp);
- return result;
- }
复制代码 执行结果:通过
显示详情
执行用时 :4 ms, 在所有 C 提交中击败了70.47%的用户
内存消耗 :6 MB, 在所有 C 提交中击败了100.00%的用户
|
|