Create 14. Longest Common Prefix.md

This commit is contained in:
唐树森 2018-10-05 10:26:09 +08:00 committed by GitHub
parent 898a72d04c
commit fdbb097d66
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,27 @@
# [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 代表重复次数
}
}
};
```