Wednesday, May 15, 2013
Leetcode: Longest Common Prefix in C++
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
string longestCommonPrefix(vector<string> &strs) {
if(strs.size()==0)
return "";
string result = strs[0];
string tmp = "";
for(int i=1;i<strs.size();i++)
{
int k=0;
tmp = "";
while(k<strs[i].size()&&k<result.size())
{
if(strs[i][k] == result[k])
{
tmp+=result[k];
}
else
break;
k++;
}
result = tmp;
}
return result;
}
Labels:
String/Number
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment