Leetcode No.14 Longest Common Prefix最长公共前缀(c++实现)
1. 题目
1.1 英文题目
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 "".
1.2 中文题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
1.3输入输出
| 输入 | 输出 |
|---|---|
| strs = ["flower","flow","flight"] | "fl" |
| strs = ["dog","racecar","car"] | "" |
1.4 约束条件
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
2. 分析
2.1 一般方法
看到这道题,最简单的方法就是两层for循环,最外层是对第一个字符串进行遍历(其实第几个字符串都无所谓),内层是对字符数组进行遍历,意思也就是先看所有字符串第一个元素是否都一样,再看第二个,第三个,以此类推,当遇到有不同的时候,就可以跳出外层循环。代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
for (unsigned int i = 0; i < strs[0].size(); i++)
{
unsigned int count = 0;
for (unsigned int j = 0; j < strs.size(); j++)
{
char temp = strs[0][i];
if (i != strs[j].size() && strs[j][i] == temp)//
count++;
else
goto here;
if (count == strs.size())
ans += strs[0][i];
}
}
here:
return ans;
}
};
2.2 改进算法(贼好使)
上述算法使用goto跳出两层循环,而goto的使用很多人是不太推荐使用的,同时联想到for循环的第二项就是一个判断语句,因此可以将goto判断语句改到for循环里,具体代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
for (unsigned int i = 0; i < strs[0].size(); i++)
{
unsigned int count = 1;
unsigned int j = 1;
int temp = strs[0][i];
for (; j < strs.size() && i != strs[j].size() && strs[j][i] == temp; j++)
count++;
if (count == strs.size())
ans += strs[0][i];
else
break;
}
return ans;
}
};
这个算法时间消耗0ms,空间消耗9M,非常不错!

浙公网安备 33010602011771号