题目描述
给定一个字符串数组 strs,寻找它们的最长公共前缀。如果不存在公共前缀,则返回空字符串 ""。
示例
示例 1
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2
输入:strs = ["dog","racecar","car"]
输出:""
解释:字符串数组中没有共同前缀,因此返回空字符串。
限制条件
- 数组长度
1 <= strs.length <= 200 - 字符串长度
0 <= strs[i].length <= 200 - 所有字符串均为小写英文字母
解题思路与实现方法
方法 1:横向扫描法
将第一个字符串作为初始公共前缀,逐一与数组中的其他字符串对比,通过缩减前缀长度来保证公共性。最终得到的是所有字符串的最长公共前缀。
代码实现
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = strs[0]; // 初始前缀
for (int i = 1; i < strs.size(); ++i) {
int j = 0; // 比较前缀与当前字符串的公共部分
while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) {
++j;
}
prefix = prefix.substr(, j);
(prefix.()) ;
}
prefix;
}
};
{
Solution s;
vector<string> strs = {, , };
cout << s.(strs) << endl;
;
}


