My accepted solution with SORT


  • 0
    M
     public String longestCommonPrefix(String[] strs) {
    
        if(strs.length==0) return "";
        if(strs.length==1) return strs[0];
        Arrays.sort(strs);
        String s1 = strs[0];
        String s2 = "";
        
        for (int index=1;index<strs.length;index++) {
            if(!s1.equals(strs[index])) {
                s2 = strs[index];
            }
        }
        
        for(int i=0;i<Math.min(s1.length(),s2.length());i++) {
            if(s1.charAt(i)!=s2.charAt(i)) {
                return (s1.substring(0,i));
            }
        }
        return s1;
    }

Log in to reply
 

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