leetcode 14 Longest Common Prefix C++实现
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.
bool cmp(const string& s1, const string& s2)
{
return s1.size()<s2.size();
}
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int i,j;
string result="";
if(strs.size()==0)
return "";
sort(strs.begin(),strs.end(),cmp);//排序,按照字符串的长度大小
//i代表第i个字符串,j代表字符串中第j个字符,容器中最长的string长度已求得。
for(j=0;j<strs[strs.size()-1].length();j++)
{
i=0;//每次循环开始之前将i置0
while(i<(strs.size()-1)&&strs[i][j]==strs[i+1][j])
{
i++;
}
if(i==strs.size()-1)//所以字符串同一个位置的字符匹配完成。
result+=strs[i][j];
else//否则立刻break掉循环,直接输出结果
break;
}
return result;
}
};