解题思路:
求最长公共前缀也就是枚举字符串数组中每两个进行对比找公共的前缀。
这里面有两个trick:
- 1.当字符串数组为空时,最长公共前缀也为空;
- 2.当字符串数组为1个字符串时,最长公共前缀为该字符串。
Code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans="";
if (strs.size() == 0) {
return ans;
}
else if (strs.size() == 1) {
ans = strs[0];
return ans;
}
else {
for (int i = 0, j = 0; i < strs[0].length(), j < strs[1].length(); i++, j++) {
if (strs[ 0 ][ i ] == strs[ 1 ][ j ]) {
ans += strs[ 0 ][ i ];
}
else {
break;
}
}
for (int i = 2; i < strs.size(); i++) {
for (int j = 0, k = 0; j < strs[i].length(), k < ans.length(); j++, k++) {
if (strs[ i ][ j ] == ans[ k ]) {
continue;
}
else {
ans.erase(k);
break;
}
}
}
return ans;
}
}
};
int main() {
Solution solution;
vector<string> str;
string string1, result;
while (cin >> string1 ) {
str.push_back(string1);
}
result = solution.longestCommonPrefix(str);
cout << result << endl;
return 0;
}





近期评论