llllmz

导航

93. 复原 IP 地址c

leetcode调试功能真香啊,效率高了不少。但钱包也变扁了。。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

char temp[30];
int top=0;
bool judge(char* s,int head,int tail){
    if(head >tail) return false;
    if(head==tail){
        int t=s[head]-'0';
        if(t>=0&&t<=9) return true;
        return false;
    }
    if(s[head]=='0') return false;
    int sum=0;
    for(;head<=tail;head++){
        if(s[head]>'9'||s[head]<'0') return false;
        sum=sum*10+s[head]-'0';
    }
    if(sum>255) return false;
    return true ;
}

void dfs(char* s,char** array,int* returnSize,int index,int n,int count,int x){
    if(index>n) return;
    if(x>4) return;
    if(index==n&&x<4) return;
    if(index==n&&x==4){
        array[*returnSize]=(char*)malloc(sizeof(char)*(count+1));
        strcpy(array[*returnSize],temp);
        array[*returnSize][count-1]=0;
        (*returnSize)++;
        return;
    }
    for(int i=0;i<3;i++){
        int tail=index+i;
        if(tail>n) break;
        if(judge(s,index,tail)){
            for(int j=index;j<=tail;j++) temp[top++]=s[j];
            temp[top++]='.';
            dfs(s,array,returnSize,tail+1,n,count+i+2,x+1);
            for(int j=index;j<=tail+1;j++) temp[--top]=0;
        }
    }
}

char** restoreIpAddresses(char* s, int* returnSize) {
    *returnSize=0;
    int n=strlen(s);
    if(n<4)  return NULL;
    char** array=(char**)malloc(sizeof(char*)*400);
    for(int i=0;i<30;i++) temp[i]=0;   
    dfs(s,array,returnSize,0,n,0,0);
    return array;
}

结果:

posted on 2024-03-09 15:24  神奇的萝卜丝  阅读(26)  评论(0)    收藏  举报