Problem Description:
Write a function to find the longest common prefix string amongst an array of strings.
题目大意:
找出一组字符串的最长前缀。
Solutions:
从前往后依次搜索即可。
Code in C++:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
string prefix = "";
for(int i = 0;i < strs[0].length(); i++)
{
char cur = strs[0][i];
for(int j = 0 ;j < strs.size();j++){
if(strs[j][i]==cur) {
if(j==strs.size()-1) prefix+=cur;
}else return prefix;
}
}
return prefix;
}
};
近期评论