最长公共前缀
2015-06-16 20:31
330 查看
给k个字符串,求出他们的最长公共前缀(LCP)
样例
在
"ABCD"
"ABEF"
和 "ACEF"
中, LCP 为 "A"
在 "ABCDEFG",
"ABCEFG", "ABCEFA" 中, LCP 为 "ABC"
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
if(strs.empty())
{
return "";
}
int minLen=0;
for(int i=0;i<strs.size();i++)
{
if(minLen<strs[i].size())
{
minLen=strs[i].size();
}
}
string result;
int index=0;
bool same=true;
while(index<minLen&&same)
{
for(int i=1;i<strs.size();i++)
{
if(strs[i][index]!=strs[i-1][index])
{
same=false;
break;
}
}
if(same)
{
result.push_back(strs[0][index]);
index++;
}
}
return result;
}
};
样例
在
"ABCD"
"ABEF"
和 "ACEF"
中, LCP 为 "A"
在 "ABCDEFG",
"ABCEFG", "ABCEFA" 中, LCP 为 "ABC"
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
if(strs.empty())
{
return "";
}
int minLen=0;
for(int i=0;i<strs.size();i++)
{
if(minLen<strs[i].size())
{
minLen=strs[i].size();
}
}
string result;
int index=0;
bool same=true;
while(index<minLen&&same)
{
for(int i=1;i<strs.size();i++)
{
if(strs[i][index]!=strs[i-1][index])
{
same=false;
break;
}
}
if(same)
{
result.push_back(strs[0][index]);
index++;
}
}
return result;
}
};
相关文章推荐
- MVC在安卓应用,ANR,Force Close,Contentprovider实现数据共享
- log4j输出格式
- cocoa 的大招(KVC的几点强大应用记录)
- java流程图
- centos 安装gdb
- 47Exchange 2010升级到Exchange 2013-迁移地址列表&OAB
- JAVA学习笔记二
- Apache与Nginx优缺点比较
- poj 1270 Following Orders 枚举排列
- poj 1363 Rails 【栈】
- Count Complete Tree Nodes
- 抽象类与接口的区别
- Android DOM解析XML方法及优化
- OpenGL Tutorial: (1) Setting up OpenGL with Visual Studio
- java获取各种路径的方法
- UVa 572 - Oil Deposits【图DFS】
- 动规,当前时间
- 自定义Loader 和 Handler传递参数给UI线程
- 反射和动态代理
- Loader异步加载ContentProvider