###原题目
```cpp
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
```
###自己的解法
思想还是停留在c的写法,即使用了迭代器,有了容器,我还是在用c的结构化思维,这样的代码不仅冗长,而且没有可读性,并且容易出错。
```cpp
//自己的代码
string longestCommonPrefix(vector<string>& strs) {
string out;
vector<string::iterator> top;
for (auto beg=strs.begin(); beg < strs.end()-1;beg++) {
if ((*((*beg).begin()) != *((*(beg+1)).begin()))&&(beg==strs.begin()))
return "";
else if((*((*beg).begin()) == *((*(beg + 1)).begin())) && (beg == strs.end() - 2))
out.push_back(*((*beg).begin()));
if (beg ==strs.end() - 1)top.push_back((*(beg+1)).begin());
top.push_back((*beg).begin());
}
return out;
```
###网上优秀的代码与思路
####第一种方法是水平扫描
就是将``` vector<string>```中的第一个字符串拿出来,一个一个与后面的字符串对比,在此中,使用find()以及substr()函数进行查找以及截取。在此中不断地比较是否能够在后面字符串找到相同,找到就跳出循环。
```cpp
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) return "";
string prefix = strs[0];
for (int i = 0; i < strs.size(); i++) {
while (strs[i].find(prefix) != 0) {
prefix = prefix.substr(0, prefix.size() - 1);
if (prefix.empty())return "";
}
}
return prefix;
}
};
```
####其他优秀代码
```cpp
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty() == 1) return "";
else {
int min = strs[0].length();
for (int i = 1; i < strs.size(); i++) {
if (min > strs[i].length())
min = strs[i].length();
for (int j = 0; j < min; j++) {
if (strs[i][j] != strs[i - 1][j]) {
min = j;
break;
}
}
}
return strs[0].substr(0, min);
}
}
};
```
####自己的思考
这次的解题思路就是先将第一个字符串纳入,然后在不断的比较中,一段段的删除,在其中用到了find以及substr。自己以后一定要多想的是容器自带的各种操作。
LeetCode-Easy-Longest Common Prefix
原文:https://www.cnblogs.com/Yekko/p/12130113.html