Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created October 14, 2018 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/9125b21afc6be22d44366ce3ad4a532d to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/9125b21afc6be22d44366ce3ad4a532d to your computer and use it in GitHub Desktop.
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len_s = strs.size();
if(len_s == 0) return "";
return longestCommonPrefix(strs, 0, len_s - 1);
}
string longestCommonPrefix(vector<string>& strs, int l, int r){
if(l == r){
return strs[l];
}
else{
int mid = (l + r)/2;
string l_part = longestCommonPrefix(strs, l, mid);
string r_part = longestCommonPrefix(strs, mid+1, r);
return calculateCommonPrefix(l_part, r_part);
}
}
string calculateCommonPrefix(string& l, string& r){
int minLen = min(l.size(), r.size());
for(int i = 0; i < minLen; i++){
if(l[i] != r[i])
return l.substr(0, i);
}
return l.substr(0, minLen);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment