LeetCode/solutions/14. Longest Common Prefix.md
2019-09-13 23:08:41 +08:00

28 lines
1.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description/)
# 思路
求字符串数组的最长公共前缀。
纵向遍历字符串,即第一次比较所有字符串的第一个字符,第二次比较所有字符串的第二个字符...直到字符串不相等或者超出某个字符串的长度时退出循环。
注意:
append函数可以用来在字符串的末尾追加字符和字符串。由于string重载了运算符也可以用+=操作实现。
# C++
``` 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 代表重复次数
}
}
};
```