【算法day13】最长公共前缀
最长公共前缀
https://leetcode.cn/problems/longest-common-prefix/submissions/612055945/
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
// 遍历每个字符串的前i个字符
string ans = "";
char ch = strs[0][0];
for (int i = 0;;) {
for (int j = 0; j < strs.size(); j++) {
if (strs[j].size() <= i || strs[j][i] != ch) {
return ans;
}
}
ans += ch;
i++;
if (strs[0].size() > i) {
ch = strs[0][i];
}
}
return ans;
}
};