My java solution using recursion


  • 0
    Z
     public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
    	if(strs.length==1) return strs[0];
    	String res = "";   
    	String first = strs[0];
    	String[] rest = Arrays.copyOfRange(strs,1,strs.length);
    	String ss = longestCommonPrefix(rest);
    	for (int i = 0; i < Math.min(first.length(),ss.length()); i++) {
    		if(first.charAt(i)!=ss.charAt(i)){
    			break;
    		}
    		res+=first.charAt(i);
    	}
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.