【题目】
Write a function to find the longest common prefix string amongst an array of strings.
【分析】
从0开始,对每一个位置比较所有的字符串,如果有不相等的则停止匹配。
【代码】
/*--------------------------------------------------------------
* 日期:2015-08-30
* 作者:SJF0115
* 题目: 14.Longest Common Prefix
* 来源:http://oj.leetcode.com/problems/longest-common-prefix/
* 结果:AC
* 来源:LeetCode
------------------------------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
int size = strs.size();
if(size <= 0){
return "";
}//if
if(size == 1){
return strs[0];
}//if
bool isSucess = true;
int size1 = strs[0].size();
for(int i = 0;i < size1;++i){
for(int j = 1;j < size;++j){
// 匹配失败
if(i >= strs[j].size() || strs[0][i] != strs[j][i]){
isSucess = false;
break;
}//if
}//for
if(!isSucess){
return strs[0].substr(0,i);
}//if
}//for
return strs[0];
}
};
int main() {
Solution solution;
string str1("abcdef");
string str2("adcdefd");
string str3("abcdefe");
vector<string> vec;
vec.push_back(str1);
vec.push_back(str2);
vec.push_back(str3);
string result = solution.longestCommonPrefix(vec);
cout<<result<<endl;
return 0;
}