Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
求最长公共前缀。注意输入为空的情况。找出最短字符串,然后逐个比较即可。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(!strs.size()){
return "";
}
int minn=strs[0].length(),i,j;
for(i=1;i<strs.size();i++){
if(strs[i].length()<minn){
minn=strs[i].length();
}
}
string ans="";
for(i=0;i<minn;i++){
for(j=1;j<strs.size();j++){
if(strs[j][i]!=strs[0][i]){
return ans;
}
}
ans=ans+strs[0][i];
}
return ans;
}
};