Longest Common Prefix (leetcode 14)
2015-08-18 10:13
239 查看
Write a function to find the longest common prefix string amongst an array of strings.
寻找所有字符串的公共前缀
思路:1,先找出最短的字符串,最长长度肯定比这个要短,减少循环长度
2,将公共前缀设置为这个最短字符串。
3,循环,每找到更短的就更短的行就迭代更新最短路径
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
string longestCommonPrefix(vector<string>& strs)
{
int n = strs.size();
if(n ==0)
{
return "";
}
else if(n==1)
{
return strs[0];
}
int shortlength = strs[0].length();
int shortindex = 0;
for(int i=1; i<n; i++)
{
if(strs[i].length() <shortlength)
{
shortlength = strs[i].length();
shortindex = i;
}
}
if(shortlength ==0)
{
return "";
}
else
{
//char * s = new char[shortlength+1];
string shortS = strs[shortindex];
for(int i=0; i<n; i++)
{
for(int j=0; j<shortlength; j++)
{
if(strs[i][j] != shortS[j])
{
shortlength = j;
}
}
}
return shortS.substr(0,shortlength);
}
}
};
int main()
{
vector<string> s;
s.push_back("C");
s.push_back("C");
//cout<<s.size();
Solution solution;
cout<<solution.longestCommonPrefix(s)<<endl;;
return 0;
}
寻找所有字符串的公共前缀
思路:1,先找出最短的字符串,最长长度肯定比这个要短,减少循环长度
2,将公共前缀设置为这个最短字符串。
3,循环,每找到更短的就更短的行就迭代更新最短路径
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
string longestCommonPrefix(vector<string>& strs)
{
int n = strs.size();
if(n ==0)
{
return "";
}
else if(n==1)
{
return strs[0];
}
int shortlength = strs[0].length();
int shortindex = 0;
for(int i=1; i<n; i++)
{
if(strs[i].length() <shortlength)
{
shortlength = strs[i].length();
shortindex = i;
}
}
if(shortlength ==0)
{
return "";
}
else
{
//char * s = new char[shortlength+1];
string shortS = strs[shortindex];
for(int i=0; i<n; i++)
{
for(int j=0; j<shortlength; j++)
{
if(strs[i][j] != shortS[j])
{
shortlength = j;
}
}
}
return shortS.substr(0,shortlength);
}
}
};
int main()
{
vector<string> s;
s.push_back("C");
s.push_back("C");
//cout<<s.size();
Solution solution;
cout<<solution.longestCommonPrefix(s)<<endl;;
return 0;
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [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
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解