Created
February 13, 2013 01:13
-
-
Save zhoutuo/4791239 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 hidden or 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) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
string prefix = ""; | |
if(strs.size() == 0) { | |
return prefix; | |
} | |
//get the next char from first line | |
char cur; | |
int index = 0; | |
while(index < strs[0].length()) { | |
cur = strs[0][index]; | |
for(int i = 0; i < strs.size(); ++i) { | |
if(cur != strs[i][index]) { | |
return prefix; | |
} | |
} | |
++index; | |
prefix += cur; | |
} | |
return prefix; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment