mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
28 lines
1.1 KiB
Markdown
28 lines
1.1 KiB
Markdown
![]() |
# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description/)
|
|||
|
# 思路
|
|||
|
求字符串数组的最长公共前缀。
|
|||
|
纵向遍历字符串,即第一次比较所有字符串的第一个字符,第二次比较所有字符串的第二个字符...直到字符串不相等或者超出某个字符串的长度时退出循环。
|
|||
|
注意:
|
|||
|
append函数可以用来在字符串的末尾追加字符和字符串。由于string重载了运算符,也可以用+=操作实现。
|
|||
|
# C++
|
|||
|
```
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
string longestCommonPrefix(vector<string>& strs) {
|
|||
|
if(strs.size() == 0) return "";
|
|||
|
string res;
|
|||
|
int i = 0;
|
|||
|
while(1){
|
|||
|
for(int j = 0; j < strs.size(); j++){
|
|||
|
if(i >= strs[j].size()) return res; // 长度超过最短字符串的长度
|
|||
|
if(j == 0 || strs[j][i] == strs[j-1][i]) continue; // 处于第一个字符串或者与上一个字符串的当前位置字符相等
|
|||
|
else return res;
|
|||
|
}
|
|||
|
res += strs[0][i++];
|
|||
|
// res.append(1, strs[0][i++]); // 1 代表重复次数
|
|||
|
|
|||
|
}
|
|||
|
}
|
|||
|
};
|
|||
|
```
|