题目描述:

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

读入一个char**和字符串的数量strSize,返回所有字符串前面相同的字符(char*类型).

解题思路:

将每个字符串相应的字符与第1个字符串的相应字符进行比对,一样继续比对,不一样则将第1个字符串当前位置的字符变为'\0',输出。

除此之外也要考虑到strsSize为0的情况和读取的当前字符串的相应字符为空的情况(其中第1个字符串和其他字符串的情况也要分开考虑).

代码:

 1 char* longestCommonPrefix(char** strs, int strsSize) {
 2     if(strsSize==0){
 3         char *p=(char*)malloc(4);
 4         return p;
 5     }
 6     int count = 0;//用于计数相同字符的个数
 7     bool flag = 0;//跳出标志,1跳出
 8     while (1) {
 9         if (flag == 1)
10             break;
11         for (int i = 0; i<strsSize; i++) {
12             if (strs[i][count] == '\0') {
13             //当前字符串的相应字符为空时
14                 flag = 1;
15                 if(i!=0)
16                 //不是第一个字符串的情况
17                     strs[0][count] = '\0';
18                 break;
19             }
20             if (i != 0) {
21                 if (strs[i][count] != strs[0][count]) {
22                     flag = 1;
23                     strs[0][count] = '\0';
24                     break;
25                 }
26             }
27         }
28         count++;
29     }
30     return strs[0];
31 }        

 

posted on 2018-01-31 15:21  宵夜在哪  阅读(104)  评论(0编辑  收藏  举报