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
| class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.size()==0) return ""; else if(strs.size()==1) return strs[0]; int len = helper(strs); return strs[0].substr(0,len); } int helper(vector<string>& strs) { int mid = strs.size()/2; return getCommonPrefix(strs[0], helper(strs, 0, mid), strs[mid], helper(strs, mid, strs.size())); } int helper(vector<string>& strs, int left, int right) { if(right-left == 1) return strs[left].size(); else if (right-left == 2) return getCommonPrefix(strs[left], strs[left].size(), strs[left+1], strs[left+1].size()); int mid = (left+right)/2; return getCommonPrefix(strs[left], helper(strs, left, mid), strs[mid], helper(strs, mid, right)); } int getCommonPrefix(string& s1, int len1, string& s2, int len2) { int maxLen = min(len1, len2); int commonLen = 0; for(int i=0; i<maxLen; ++i) { if(s1[i]==s2[i]) commonLen++; else break; } return commonLen; } };
|