Java solution accept 51.8%


  • 0
    P
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int minLen = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++) {
            String itemStr = strs[i];
            if (itemStr.length() < minLen) {
                minLen = itemStr.length();
            }
        }
        StringBuilder prefixStr = new StringBuilder(strs[0].subSequence(0, minLen));
    
        for (int i = 0; i < strs.length; i++) {
            String itemString = strs[i];
            for (int j = 1; j < minLen; j++) {
                if (itemString.charAt(j) != prefixStr.charAt(j)) {
                    prefixStr = new StringBuilder(itemString.substring(0, j));
                    minLen = j;
                }
            }
        }
        return prefixStr.toString();
    }

Log in to reply
 

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