[LeetCode]14. Longest Common Prefix
题目描述
思路
比较公共前缀,遍历即可
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0)
return "";
if (strs.size() == 1)
return strs[0];
string res;
bool stop = false;
for (int j = 0; j < strs[0].size(); ++j) {
for (int i = 1; i < strs.size(); ++i) {
if (j >= strs[i].size()) {
stop = true;
break;
}
if (strs[i][j] != strs[0][j]) {
stop = true;
break;
}
}
if (stop)
break;
res += strs[0][j];
}
return res;
}
};
int main() {
vector<string> strs = { "abc", "", "ab" };
Solution s;
cout << s.longestCommonPrefix(strs) << endl;
system("pause");
return 0;
}
本文详细解析了LeetCode第14题“最长公共前缀”的解题思路及C++实现代码。通过遍历字符串数组,逐字符比较来找出最长公共前缀。
304

被折叠的 条评论
为什么被折叠?



