首先注意下前缀/后缀和子串的区别:
"前缀"和"后缀": "前缀"指除了最后一个字符以外,一个字符串的全部头部组合;
"后缀"指除了第一个字符以外,一个字符串的全部尾部组合。
"子串":可以出现在一个字符串的任意位置的子字符串;
比如"abcde" ,"a"、"ab"、"abc"、"abcd"是前缀,而任意连续位置"bc"、"abc"、"cde"等都属于子串!!
今天就是忘了它们的区别,吃了一大亏;当时就想,怎么一简单题还弄出这么多花样。。。
思路:最长公共前缀肯定蕴含在最短子串中,所以for(i from 0 to 最短子串的长度) ,把每个字符串对应位置的字符都与它比较,如果出现不相等,则0~i-1就是最长公共前缀;
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string s1, string s2) //用于找到最短字符串的比较函数
{
return s1.length() < s2.length();
}
string longestCommonPrefix(vector<string> &strs)
{
string res = "";
if (strs.size() == 0)
return res;
if (strs.size() == 1)
return strs[0];
//把vector中得字符串按长度大小排序
sort(strs.begin(), strs.end(), cmp);
//只需要把按下标将最小得字符串与后面逐步比较
res = strs[0]; //最小字符串
for (int i = 0; i < res.length(); i++)
{
for (int j = 0; j < strs.size(); j++)
{
if(res[i]!=strs[j][i]) //每个字符串的对应位置与res对应位置相比较
return res.substr(0,i) ;//substr(起始位置,字符个数)
}
}
}
int main()
{
vector<string> test;
test.push_back("flight");
test.push_back("flowr");
test.push_back("flow");
cout<<longestCommonPrefix(test);
return 0;
}