Created
November 15, 2013 06:15
-
-
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.
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) { | |
// 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