Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created July 5, 2013 07:28
Show Gist options
  • Select an option

  • Save luoxiaoxun/5932655 to your computer and use it in GitHub Desktop.

Select an option

Save luoxiaoxun/5932655 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings.
C++:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(strs.size()==0) return "";
if(strs.size()==1) return strs[0];
string ret="";
int maxLen=INT_MAX;
for(int i=0;i<strs.size();i++)
if(maxLen>strs[i].size())
maxLen=strs[i].size();
for(int i=0;i<maxLen;i++){
char cur=strs[0][i];
int j;
for(j=1;j<strs.size();j++)
if(strs[j][i]!=cur)
break;
if(j!=strs.size()) break;
ret +=cur;
}
return ret;
}
};
Java:
public class Solution {
public String longestCommonPrefix(String[] strs) {
// Start typing your Java solution below
// DO NOT write main() function
if(strs.length==0) return "";
if(strs.length==1) return strs[0];
String ret="";
int maxLen=Integer.MAX_VALUE;
for(int i=0;i<strs.length;i++) maxLen=Math.min(strs[i].length(),maxLen);
for(int i=0;i<maxLen;i++){
char cur=strs[0].charAt(i);
int j;
for(j=1;j<strs.length;j++)
if(strs[j].charAt(i)!=cur)
break;
if(j!=strs.length) break;
ret +=cur;
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment