您的位置:首页 > 编程语言 > C语言/C++

LeetCode刷题(C++)——Longest Common Prefix(Easy)

2017-05-03 15:32 513 查看
Write a function to find the longest common prefix string amongst an array of strings.

本题的意思是寻找字符串数组中所有字符串的最长公共前缀

如输入:{"abcd","abcdefg","abef","abdef"}

输出结果为:"ab"

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty())
return "";
if (strs.size() == 1)
return strs[0];
int minlen = INT_MAX;
for (auto x : strs)
{
if (minlen > x.size())
minlen = x.size();
}
int i = 0;
string x = strs[0];
while (i < minlen)
{
for (auto y:strs)
{
if (x[i] != y[i])
return x.substr(0, i);
}
++i;
}
return x.substr(0, i);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息