【字符串】最长公共前缀
题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串
""
。示例:
输入: strs = [“flower”,“flow”,“flight”]
输出: “fl”输入: strs = [“dog”,“racecar”,“car”]
输出: “”
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
// 纵向比较
string longestCommonPrefix(vector<string>& strs) {
string res;
if(strs.empty()){
return res;
}
for(int i=0; i<strs[0].length(); i++){
char s = strs[0][i];
for(int j=0; j<strs.size(); j++){
// i>strs[j].length()-1 防止访问越界
if(s != strs[j][i] || i>strs[j].length()-1){
return res;
}
}
res += s;
}
return res;
}
};
int main()
{
vector<string> arr = { "flower","flow","flight" };
Solution solution;
string result = solution.longestCommonPrefix(arr);
cout << result << endl;
return 0;
}
方法二、横向比较
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}
int length = strs[0].size();
int count = strs.size();
for (int i = 0; i < length; ++i) {
char c = strs[0][i];
for (int j = 1; j < count; ++j) {
if (i == strs[j].size() || strs[j][i] != c) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
};