题目描述
题解
采用十分朴素的办法,直接取出第一个单词,依次将其的每一个字母和后面所有的单词进行比较即可。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string longestCommonPrefix(vector<string>& strs);
int main() {
vector<string> strs = { "flower","flow","flight" };
cout << longestCommonPrefix(strs);
}
string longestCommonPrefix(vector<string>& strs) {
string Common = "";
if (strs.empty())
return "";
int flag = 1;
for (int i = 0; i < strs[0].size(); i++) {
char temp = strs[0][i];
for (int j = 1; j < strs.size(); j++) {
if (strs[j][i] != temp) {
flag = 0;
break;
}
}
if (flag) {
Common = Common + temp;
}
else
{
break;
}
}
return Common;
}