编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
unsigned char c_len = strs[0].length();
if(c_len == 0)
return "";
unsigned char s_len = strs.size();
if(s_len == 1)
return strs[0];
char *ch = (char *)malloc(c_len+1); //申请内存不加1的话,leetcode会报错
memset(ch,0,c_len+1);
for(unsigned char i = 0; i < c_len; i++)
{
unsigned char j = 0;
for(; j < s_len; j++)
{
if(strs[0][i] != strs[j][i])
break;
}
if(j == s_len)
{
cout << strs[0][i];
ch[i] = strs[0][i];
}
else
{
break;
}
}
string s(ch);
free(ch);
return s;
}
};