Skip to content

Instantly share code, notes, and snippets.

@elimence
Created March 19, 2015 21:28
Show Gist options
  • Save elimence/ca8c0731224a2d5cd230 to your computer and use it in GitHub Desktop.
Save elimence/ca8c0731224a2d5cd230 to your computer and use it in GitHub Desktop.
Function to find the common prefix in a list of strings
public class PreFixer {
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("invalid arguments");
return;
}
String commongPrefix = getCommonPrefix(args);
System.out.println("Common Prefix for list is : " + commongPrefix);
}
private static String getCommonPrefix (String[] list){
int matchIndex = recursiveChecker(0, list);
return list[0].substring(0, matchIndex);
}
private static int recursiveChecker(int strIndex, String[] list){
for(int x=0; x<list.length; x++) {
if(strIndex >= list[x].length()){
return strIndex;
}
if(list[0].charAt(strIndex) != list[x].charAt(strIndex)) {
return strIndex;
}
}
return recursiveChecker(strIndex + 1, list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment