您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode