Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active August 14, 2018 05:15
Show Gist options
  • Save guolinaileen/4640646 to your computer and use it in GitHub Desktop.
Save guolinaileen/4640646 to your computer and use it in GitHub Desktop.
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string result="";
if(strs.size()==0) return result;
result=strs[0];
for(int i=1; i<strs.size(); i++)
{
for(int j=0; j<=min(result.length(), strs[i].length()); j++)
{
if(j==strs[i].length())
{
result=strs[i]; break;
}
if(result[j]!=strs[i][j])
{
result=result.substr(0, j); break;
}
}
}
return result;
}
};
public class Solution {
public String longestCommonPrefix(String[] strs) {
int length=strs.length;
if(length==0) return "";
if(length==1 || strs[0]=="" ) return strs[0];
String result=strs[0];
for(int i=1; i<length; i++)
{
if(strs[i]=="") return "";
int idx=0;
for(; idx<Math.min( result.length() , strs[i].length() ); idx++)
{
if(strs[i].charAt(idx)!=result.charAt(idx))
{
if(idx==0)
{
return "";
}
break;
}
}
result=result.substring(0, idx);
}
return result;
}
}
@biefanwo
Copy link

hi,if implementation this function with c language will be best!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment