C language Recursive


  • 1
    T

    The idea is refer to follow address
    https://discuss.leetcode.com/topic/57228/0ms-simple-c-solution

    If you use C language, you need to write more codes, such as memory malloc for string, it's inconvenient for it.

    char* dfs(char* s, int *k) 
    {
        int i=0, cnt=0, len=0;
        char * temp = NULL;
    
        char * res = (char *)malloc(sizeof(char));
        memset(res, 0, sizeof(char));
    
        while(*k < strlen(s))
        {
            //printf("Input char : %2c\n", s[*k]);
            if( ('0'<=s[*k]) && ('9'>=s[*k]) )
            {            
                cnt = cnt*10 + (s[*k]-'0');
                *k = *k + 1;
            }
            else if(s[*k] == '[')
            {
                *k = *k + 1;
                
                temp = dfs(s, k);            
                len = strlen(temp);            
                //printf("\nReturn String : (len :%3d) %s\n", len, temp);
                
                if(strlen(res)<strlen(temp))
                    res = (char *)realloc(res, cnt*len*sizeof(char)+1);
                else 
                    res = (char *)realloc(res, cnt*len*sizeof(char)+strlen(res)+1);
                
                    if(res == NULL)
                    {
                        printf("realloc is NULL, fail\n");
                    }
                    else
                    {
                        for(i=0; i<cnt; i++)
                        {
                            strncat(res, temp, len);
                            //printf("Splice String : (time:%3d) %s\n", i+1, res);
                        }
                        
                        cnt = 0;
                    }
    
            }
            else if(s[*k] == ']')
            {
                *k = *k + 1;
                return res;
            }
            else 
            {
                strncat(res, &s[*k], 1);
                if(strlen(res)>1)
                    res = (char *)realloc(res, sizeof(char)+strlen(res));
                else
                    res = (char *)realloc(res, sizeof(char));
    
                *k = *k + 1;
            }
        }
    
        return res;
    }
    
    char* decodeString(char* s) 
    {
        int k = 0;
        
        char * result = dfs(s, &k);
        result[strlen(result)] = '\0';
    
        //printf("\nGet Decode string len : %d\n", strlen(result));
    
        return result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.