} 点击复制后,将打开C知道体验页 | 编写一个函数来查找字符串数组中的最长公共前缀,保证存在。c➕➕,不用vector
时间: 2024-05-30 07:15:52 浏览: 22
#include <iostream>
#include <cstring>
using namespace std;
string longestCommonPrefix(string strs[], int n) {
string result = "";
int minLen = INT_MAX;
for (int i = 0; i < n; i++) {
int len = strs[i].length();
minLen = min(minLen, len);
}
for (int i = 0; i < minLen; i++) {
char ch = strs[0][i];
for (int j = 1; j < n; j++) {
if (strs[j][i] != ch) {
return result;
}
}
result += ch;
}
return result;
}
int main() {
string strs[] = {"abcd", "abcef", "abcpqr"};
int n = sizeof(strs) / sizeof(strs[0]);
string prefix = longestCommonPrefix(strs, n);
cout << "Longest Common Prefix: " << prefix << endl;
return 0;
}