编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
总结:
-
不熟悉c++ string的操作
-
可当做二维数组遍历,str[i][j]
-
size()=lenth()
-
substr(pos,count),返回自pos起count个字符的子串,为空自动返回空字符串“”
-
边界值未提前考虑
-
节约空间,能不定义变量则不定义,无需定义变量common来存储公共前缀,只需将第一个字符串作为初始公共前缀,返回其子串即可
思路:
-
边界:当strs为空时直接返回空字符串
-
纵向遍历,以str[0]作为初始公共前缀,遍历数组中的其他字符串,比较每一位字符:考虑临界点,不相等时,返回之前的所有子串;遍历到某一字符串末尾时,结束遍历,返回之前的所有子串;如果都相等,则顺利的返回初始公共前缀str[0]
string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();
if(len==0)
return "";
int len1=strs[0].length();
string common=strs[0];
int count=0;
for(int i=0;i<len1;i++)
{
char c=strs[0][i];
for(int j=1;j<len;j++)
{
if(strs[j][i]!=c||strs[j].length()==i)
return common.substr(0,i);
}
}
return common;
}