最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

  • 示例 1:

    输入:strs = ["flower","flow","flight"]
    输出:"fl"
  • 示例 2:

    输入:strs = ["dog","racecar","car"]
    输出:""

    解释:输入不存在公共前缀。

提示:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string result;
if (strs.size() < 1) {
return result;
}
result = strs[0];
for (int i = 1; i < strs.size(); ++i) {
int index = 0;
while (index < result.size() && index < strs[i].size()) {
if (result[index] != strs[i][index]) {
break;
}
index++;
}
result = result.substr(0, index);
if (index == 0)
return result;
}
return result;
}
};

int main() {
vector<string> strs = {"flower", "flow", "flight"};
std::cout << Solution().longestCommonPrefix(strs) << std::endl; // fl
strs = {"dog", "racecar", "car"};
std::cout << Solution().longestCommonPrefix(strs) << std::endl; // ""
}