Skip to content

Instantly share code, notes, and snippets.

@daifu
Created February 25, 2013 18:53
Show Gist options
  • Select an option

  • Save daifu/5032239 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5032239 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings.
public class Solution {
public String longestCommonPrefix(String[] strs) {
// Start typing your Java solution below
// DO NOT write main() function
int size = strs.length;
if(size == 0) {
return "";
}
String common = strs[0];
for (int i = 1; i < size; i++){
String ahead = strs[i];
common = longestCommonPrefixHelper(common, ahead);
}
return common;
}
public String longestCommonPrefixHelper(String common, String next) {
int size = (common.length() >= next.length()) ? next.length() : common.length();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < size; i++) {
if(common.charAt(i) == next.charAt(i)) {
sb.append(common.charAt(i));
} else {
i = size;
}
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment