My C code, 0ms by vertical compare


  • 0
    W
    char* longestCommonPrefix(char** strs, int strsSize) {
    if (strs == NULL || *strs == NULL)
        return "";
        
    int len = strlen(strs[0]);
    int max = 0, loop = 1, i;
    char* ps = strs[0], *ret;
    
    while(max < len) {
        for (i = 1; i < strsSize; i++) {
            if (strs[i][max] != strs[0][max]) {
                len = max;
                break;
            }
        }
        if (max < len) max++;
    }
    
    ret = (char*)malloc(sizeof(char)*(max+1));
    for (i = 0; i < max; i++) ret[i] = strs[0][i];
    
    ret[max] = '\0';
    
    return ret;
    }

  • 0
    G
    char* longestCommonPrefix(char** strs, int strsSize) {
       if(strs==NULL || strs[0]==NULL || strs[0][0]=='\0') {
          return "";
       }
    
       int index=strlen(strs[0]);
       int i,j=0;
       int same=1;
       char *prefix=malloc(strlen(strs[0])*sizeof(char));
       if(prefix==NULL) {exit(-1);}
       strcpy(prefix, strs[0]);
    
       for(i=0;i<strlen(strs[0]);i++) {
          for(j=1;j<strsSize;j++) {
             // printf("%c and %c\n", strs[0][i], strs[j][i]);
             if(strs[0][i]!=strs[j][i]) {
                same=0;
                break;
             }
          }
    
          if(same==0) {
             index=i;
             // printf("index is %d\n", index);
             break;
          }
       }
    
       prefix[index]='\0';
       // printf("prefix is %s\n", prefix);
    
       return prefix;
    }

  • 0
    W

    Same logic, but better than my codes, helpful,thanks.


Log in to reply
 

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