Accepted Java code without any additional data structures


  • 0
    J
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        int min = Integer.MAX_VALUE;
        String prefix;
    
        // find the shortest element
        for(String str : strs){
            if(str.length() < min){
                min = strs[i].length();
                prefix = str;
            }
        }
    
        for(String str : strs){
            while(!prefix.equals(str.substring(0,prefix.length())) && !prefix.equals("")){
                prefix = prefix.substring(0,prefix.length()-1);
            }
        }
        
        return prefix;
    }

Log in to reply
 

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