My C solution, it do well in my ubuntu, but it is not passed! why!


  • 0
    C

    I fail at "glzamzp" , 5.

    char* convert(char* s, int numRows)
    {

    char* result = NULL;
    
    int i        = 0;
    int j        = 0;
    int pos      = 0;
    int step1    = 0;
    int step2    = 0;
    int numChars = strlen(s);
    
    if (numRows == 1)
    {
        return s;
    }
    
    if ((NULL != s) && (numRows > 1))
    {
        result = (char*)malloc(sizeof(char) * numChars);
        for (i = 0; i < numRows; i++)
        {
            step1 = (numRows - i - 1) * 2;
            step2 = i * 2;
            pos   = i;
            
            result[j++] = s[pos];
            
            while(1)
            {
                pos += step1;
                if (pos > numChars)
                {
                    break;
                }
                
                if ('\0' == s[pos])
                {
                    break;
                }
                
                if (step1 > 0)
                {
                    result[j++] = s[pos];
                }
                
                pos += step2;
                if (pos > numChars)
                {
                    break;
                }
                
                if ('\0' == s[pos])
                {
                    break;
                }
                
                if (step2 > 0)
                {
                    result[j++] = s[pos];
                }
            }
        }
        result[j] = '\0';
    }
    
    return result;
    

    }


  • 0
    1

    你在为result数组分配空间时,分配的空间大小应该为numChars+1,而不是numChars,因为你在最后又添加结束符 '\0' !


  • 0
    C

    谢谢啊!犯了一个低级错误。


Log in to reply
 

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