Last active
December 15, 2015 15:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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