编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z
。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0)
return "";
// 待比较的字符串index
int index = 0;
// 当前字符
string judge = strs[0];
while(index < judge.size()){
for(int i=1; i<strs.size(); i++){
// 超过index
if(strs[i].size() <= index){
return judge.substr(0,index);
}
// 比较相同
if(strs[i][index] != judge[index])
return judge.substr(0,index);
}
index ++;
}
return judge.substr(0,index);
}
};