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);
}
};
本题的意思是寻找字符串数组中所有字符串的最长公共前缀
如输入:{"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);
}
};
相关文章推荐
- [LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
- Leetcode[Easy] - Longest Common Prefix
- leetcode_14_Longest Common Prefix (easy)
- leetcode 14 Longest Common Prefix C++
- LeetCode 之 Longest Common Prefix — C++实现
- 【leetcode c++】14Longest Common Prefix
- LeetCode-Easy-Java-Longest Common Prefix
- LeetCode上Longest Common Prefix的C++解法
- [C++]LeetCode 14: Longest Common Prefix(最长公共前缀)
- leetcode_c++:Longest Common Prefix(014)
- [C++]LeetCode: 21 Longest Common Prefix
- [Leetcode 14, Easy] Longest common prefix
- LeetCode-Easy刷题(4) Longest Common Prefix
- leetcode第十四题(easy)——Longest Common Prefix
- LeetCode 14 — Longest Common Prefix(C++ Java Python)
- leetcode_Longest Common Prefix_easy
- 【Leetcode-easy】Longest Common Prefix
- LeetCode-Easy部分中标签为String 14. Longest Common Prefix
- LeetCode-14-Longest Common Prefix(Number/Vector/String)-Easy
- leetcode: 14.Longest Common Prefix