1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include <iostream> #include <vector> #include <algorithm>
using namespace std;
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if (strs.size()==0) { return ""; } vector<int> minLen; for (int i = 0; i < strs.size(); ++i) { minLen.push_back(strs[i].size()); } sort(minLen.begin(),minLen.end()); int min=minLen[0]; int i=0,flag=1; for (; i < min&&flag; ++i) { for (int j = 0; j < strs.size()-1; ++j) { if (strs[j][i]!=strs[j+1][i]) { flag=0; i--; break; } } } if (i==0){ return ""; } return strs[0].substr(0,i); } };
int main() { vector<string> v={"a"}; Solution s; cout<<s.longestCommonPrefix(v)<<endl; return 0; }
|