Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 13, 2013 01:13
Show Gist options
  • Save zhoutuo/4791239 to your computer and use it in GitHub Desktop.
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.
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