每日一练之Longest Common Prefix【LeetCode No.14】——求字符串的最长公共前缀
题目:Write a function to find the longest common prefix string amongst an array of strings.
分析:只需用第一个字符串与后面的进行比较,最大长度不能大于第一个字符串的长度
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size()==0){
return "";}
string prefix="";
for(int i=0;i<strs[0].length();i++){
for(int j=0;j<strs.size();j++){
if(strs[0][i]!=strs[j][i]){
return prefix;
}
}
prefix+=strs[0][i];
}
return prefix;
}
};