class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) {
return "";
}
//1.横向扫描
/*string pre = strs[0];
int i = 0;
for (; i < strs.size(); i++) {
while (strs[i].find(pre) != 0) {
pre = pre.substr(0, pre.size() - 1);
}
}
return pre;*/
//2.纵向扫描
string rst = "";
int pos = 0;
int i = 0;
while (1) {
if (i >= strs[0].size()) break;
char ch = strs[0][i];
int j = 1;
while (j < strs.size() && i < strs[j].size()) {
if (strs[j][i] == ch) {
j++;
}
else {
break;
}
}
if (j != strs.size()) break;
rst += ch;
i++;
}
return rst;
}
};
【字符串】leetcode.14 最长公共前缀
最新推荐文章于 2022-04-19 18:01:12 发布