Given a list of strings, my task is to find the common prefix.
Sample input: ["madam", "mad", "mast"]
Sample output: "ma"
Sample input: ["question", "method"]
Sample output: ""
Below is my solution, I'd be happy for help improving the algorithm (I'm open to totally different approaches) or general code improvement tips. Thanks :)
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);
}
}