编写一个函数来查找字符串数组中的最长公共前缀,保证存在。c➕➕,不用容器
时间: 2024-04-29 13:23:53 浏览: 84
C语言求两个字符串的最长公共子串
5星 · 资源好评率100%
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
string res = "";
if (strs.empty()) return res;
int len = strs[0].size();
for (int i = 0; i < len; i++) {
char c = strs[0][i];
for (int j = 1; j < strs.size(); j++) {
if (i >= strs[j].size() || strs[j][i] != c) {
return res;
}
}
res += c;
}
return res;
}
int main() {
vector<string> strs = {"flower", "flow", "flight"};
string res = longestCommonPrefix(strs);
cout << res << endl;
return 0;
}
```
阅读全文