Extra char like "a�c" in output


  • 0
    G

    i`m blocked by this case :

     {Input:
    ["a","ac"]}
    

    i submit twice with the same code ,but the output is different:

    Output:
    "a�c"
    
    Output:
    "aY1"
    

    i comple in my xcode and get the expected output "a" all the time, So why there is an extra char '�c' ?

    Here is my code:

     char* longestCommonPrefix(char** strs, int strsSize) {
              if (strsSize < 1) {
                return "";
            }
            int singleLength = (int)strlen(strs[0]);
            if (singleLength == 0) {
                return "";
            }
            
            char* longestPrefix;
            longestPrefix = malloc(sizeof(char)*(singleLength+1));
            longestPrefix[0] = '\0';
            
            
            
            for (int i = 0; i< singleLength; i++) {
                
                char commonChar = strs[0][i];
        
                for (int j = 1; j< strsSize; j++) {
                    
                    if (commonChar != strs[j][i]) {
                        return longestPrefix;
                    }
                    
                }
                longestPrefix[i] = commonChar;
            }
        
            
            return longestPrefix;
        }

Log in to reply
 

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