题解 | #最长公共前缀#C+暴力解法
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
看没人用C做这个题,写一下自己的思路
- 找到最短字符串。
- 用最短字符串和其它字符串比较,找到公共的子序列
- 时间复杂度:N+N*M
char* Com_str12(char* s1, char* s2, int n) {
char* s = (char*)malloc(sizeof(char) * 400);
int i = 0, j = 0;
if (s1[0] != s2[0]) {
s = "";
return s;
}
while (i < n) {
if (s1[i] == s2[i]) {
s[i] = s1[i];
} else {
break;
}
i++;
}
return s;
}
char* longestCommonPrefix(char** strs, int strsLen ) {
// write code here
//暴力解法思路,先找出最短的字符串的长度,然后截取最长看是否相等,如果不是,就减一
int i = 0, min_len = 5001, j = 0, max = 5001, len1 = 0, g = 0;
//char* s1 = (char*)malloc(sizeof(char) * 5000);
char* s2 = (char*)malloc(sizeof(char) * 400);//需要提前申请地址
char* s3 = (char*)malloc(sizeof(char) * 400);
if (strsLen == 0 || strs == NULL) {
return "";
}
if (strsLen == 1) {
return strs[0];
}
for (i = 0; i < strsLen; i++) {//找最短字符串
len1 = strlen(strs[i]);
if ( len1 < min_len) {
min_len = strlen(strs[i]);
// strcpy(s1, strs[i]);
g = i;
}
}
for (i = 0; i < strsLen ; i++) {//和最短字符串比较
if (i != g) {
s2 = Com_str12(strs[i], strs[g], min_len);
if (max > strlen(s2)) {
max = strlen(s2);
strcpy(s3,s2);
}
}
}
return s3;
}