LeetCode 14 — Longest Common Pre
2018-10-26 本文已影响0人
帅气的昵称都有人用了
题目描述
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.
Note:
All given inputs are in lowercase letters a-z.
这是一道看起来比较简单的题目,要求就是找到最长的相同前缀,因此,我们需要做的事情肯定就主要是遍历了,在这道题里面,我们可以借助数组进行遍历。
问题解决的方法也很简单,直接po代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
{
return "";
}
for(int i = 0; i < strs[0].size(); i++)
{
for(int j = 0; j < strs.size(); ++j)
{
if(strs[j].size() < i || strs[j][i] != strs[0][i])
return strs[0].substr(0, i);
}
}
return strs[0];
}
};
这道题真的很简单啊~