【leetcode】93. 复原IP地址

 

void recursion(char * s,int slen,char** arr,int* returnSize,char* temp,int tlen,int cnt,int start,int len){
    if(cnt==4){
        if(tlen==len+4){
            arr[(*returnSize)]=(char*)calloc(tlen,sizeof(char));
            memcpy(arr[(*returnSize)],temp,tlen-1);
            (*returnSize)++;
        }
        return;
    }
    for(int i=start; i<=3 && slen+i<=len; i++){
        if(i>=2 && s[0]=='0')
            break;
        if(i==3 && (s[i-3]-'0')*100+(s[i-2]-'0')*10+(s[i-1]-'0') >255)
            break;
        memcpy(temp+tlen,s,i);
        strcat(temp,".");
        recursion(s+i,slen+i,arr,returnSize,temp,tlen+i+1,cnt+1,start,len);
        memset(temp+tlen,0,i+1);
    }
}
char ** restoreIpAddresses(char * s, int* returnSize){
    int len=strlen(s);
    char** arr=(char**)calloc(1000,sizeof(char*));
    char temp[1000]={0};
    *returnSize=0;
    if(len>12 || len<4) return NULL; 
    int start=(len<11)?1 :(len<12)?2 :3;
    recursion(s,0,arr,returnSize,temp,0,0,start,len);
    return arr;
}

 

posted @ 2020-12-14 12:13  温暖了寂寞  阅读(89)  评论(0编辑  收藏  举报