Write a function to find the longest common prefix string amonst an array of strings.
If there is no common prefix, return an empty string "".
想法:
逐一比對字串的開頭字母
如果一樣,比對下一個字母;如果不一樣,將第一個字串的此字設為'\0',並回傳此字串。
程式碼:
char* longestCommonPrefix(char** strs, int strsSize) {
int i = 0, j = 0;
int cnt = 0;
int flag = 0;
char cmpchar;
while (strs[0][i]) {
i++;
}
while (strs[0][cnt]) {
cmpchar = strs[0][cnt];
for (i=1; i<strsSize; i++) {
if (!strs[i][cnt] || cmpchar != strs[i][cnt])
{
flag = 1;
break;
}
}
if (flag != 0)
{
strs[0][cnt] = '\0';
break;
}
cnt++;
}
return strs[0];
}