[leetcode] 【字符串】 14. Longest Common Prefix
2016-06-15 11:10
405 查看
Write a function to find the longest common prefix string amongst an array of strings.
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()||strs[0].size()==0)
return "";
string prefix=strs[0];
for(int i=1;i!=strs.size();i++)
{
if(prefix.size()==0||strs[i].size()==0)
return "";
int len=prefix.size()>strs[i].size() ? prefix.size():strs[i].size();
int j=0;
for(;j!=len;j++)
{
if(prefix[j]!=strs[i][j])
break;
}
prefix=prefix.substr(0,j);
}
return prefix;
}
};第二个是纵向匹配,对比每一组的一个字符,然后再对比每一组的下一个字符。如此直到有的组的字符不符为止。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
for(int j=0;j<strs[0].size();j++)
{
for(int i=1;i<strs.size();i++)
{
if(strs[0][j]!=strs[i][j]) return strs[0].substr(0,j);
}
}
return strs[0];
}
};
题意
找字符串数组里的最长公共前缀。题解
解法很多,第一个是横向匹配,第一组与每一组对比,每比一次取最小公共前缀。匹配完则得到所有公共前缀。能通过,但是比较慢class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()||strs[0].size()==0)
return "";
string prefix=strs[0];
for(int i=1;i!=strs.size();i++)
{
if(prefix.size()==0||strs[i].size()==0)
return "";
int len=prefix.size()>strs[i].size() ? prefix.size():strs[i].size();
int j=0;
for(;j!=len;j++)
{
if(prefix[j]!=strs[i][j])
break;
}
prefix=prefix.substr(0,j);
}
return prefix;
}
};第二个是纵向匹配,对比每一组的一个字符,然后再对比每一组的下一个字符。如此直到有的组的字符不符为止。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
for(int j=0;j<strs[0].size();j++)
{
for(int i=1;i<strs.size();i++)
{
if(strs[0][j]!=strs[i][j]) return strs[0].substr(0,j);
}
}
return strs[0];
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解