Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Last active December 15, 2015 15:29
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 zhoutuo/5282293 to your computer and use it in GitHub Desktop.
Save zhoutuo/5282293 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings.
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if(strs.size() == 0) {
return "";
}
string prefix;
int index = 0;
while(true) {
char* cur = NULL;
for(int i = 0; i < strs.size(); ++i) {
string& curStr = strs[i];
if(curStr.length() == index) {
return prefix;
} else {
if(cur == NULL) {
cur = new char(curStr[index]);
} else {
if(*cur != curStr[index]) {
return prefix;
}
}
}
}
++index;
if(cur != NULL) {
prefix.push_back(*cur);
delete cur;
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment