2015年7月31日 星期五

LEET code--Longest Common Prefix

Longest Common Prefix


Write a function to find the longest common prefix string amongst an array of strings.

找出一堆字串中
起始一起出現的值

s1: abaccc
s2: abccc
s3: abrrr

LCP=ab   三個都從ab開始


因為會有空字串  要注意
用char *ans 最好都要malloc 
strdup 會把你傳進去的字串 用malloc 一個空間把string複製過去回傳指標回來
感覺很好用!!!


char* longestCommonPrefix(char** strs, int strsSize) {
    char *ans="";
   
    int strindex=0,index=0;
    if(strsSize ==0)return ans;
    if(strsSize ==1)return strs[0];
    if(strs[0][index]=='\0')return ans;
   
    //ans[index]=strs[0][index];
    while(1){
        for( int i = 1 ; i < strsSize ; i++ )
      {
            if( strs[0][index] != strs[i][index] || strs[0][index]=='\0'){
               
                if(index>=1){
                    ans =strdup(strs[0]);
                    ans[index]='\0';
                }
                return ans;
            }
        }
        index++;
       // ans[index]=strs[0][index];
    }
   
}

沒有留言:

張貼留言