leetcode_14_Longest Common Prefix (easy)
Longest Common Prefix
题目:
Write a function to find the longest common prefix string amongst an array of strings.
找出所有字符串的最长公共前缀。
解题:
string&&vector
http://blog.chinaunix.net/uid-26275986-id-3813890.html
//
// main.cpp
// leetcode_14
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
vector<string> prefix;
vector<int> prefixNum;
for(int index = 0;index<strs.size();index++){
string str = strs[index];
vector<string>::size_type num = str.find(' ',0);
string nowPrefix = str.substr(0,num);
int flag = 0;
for(int i = 0;i<prefix.size();i++){
if(nowPrefix == prefix[i]){
flag = 1;
prefixNum[i]++;
break;
}
}
if(!flag){
prefix.push_back(str);
prefixNum.push_back(1);
}
}
string longestPrefix="";
for(int index = 0;index<prefix.size();index++){
if(prefixNum[index]<2){
continue;
}
string nowPrefix = prefix[index];
if(nowPrefix.length()>longestPrefix.length()){
longestPrefix = nowPrefix;
}
}
return longestPrefix;
}
};
int main(int argc, const char * argv[]) {
Solution a;
vector<string> vec;
string str;
cout<<"请输入"<<endl;
while(cin >> str)
{
if(str=="end"){
break;
}
vec.push_back(str); //必须使用push_back()动态添加新元素
}
cout<<a.longestCommonPrefix(vec);
return 0;
}
wrong answer