My Java sol, easy understand.


  • 0
    J
    public String longestCommonPrefix(String[] strs) {
            if(strs.length == 0) return "";
            Arrays.sort(strs, (a,b) -> Integer.compare(a.length(), b.length()));
            String prefix = strs[0];
    		for(int i=1; i<strs.length; i++){
    			String s = strs[i];
    			for(int j=0; j<prefix.length();j++){
    				if(s.charAt(j) != prefix.charAt(j)){
    					prefix = s.substring(0,j);
    					break;
    				}
    			}
    		}
    		return prefix;
        }

Log in to reply
 

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