Skip to content

Instantly share code, notes, and snippets.

@safeng
Created November 15, 2013 06:15
Show Gist options
  • Save safeng/7479942 to your computer and use it in GitHub Desktop.
Save safeng/7479942 to your computer and use it in GitHub Desktop.
Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings.
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(strs.size() == 0)
return string();
if(strs.size() == 1)
return strs[0];
std::ostringstream oss;
size_t i = 0;
while(i<strs[0].length())
{
char c = strs[0][i];
size_t j = 1;
for(; j<strs.size(); ++j)
{
if(i>=strs[j].length())
break;
if(strs[j][i] != c)
break;
}
if(j == strs.size())
{
oss<<c;
++i;
}
else
break;
}
return oss.str();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment