1ms easy to understand Java solution


  • 0
    B
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0)
                return "";
            
            if (strs.length == 1) 
                return strs[0];
            
            // Simply define the max longest prefix length as minimum word length
            int maxLength = Integer.MAX_VALUE;
            for (String word : strs) {
                if (word.length() < maxLength) {
                    maxLength = word.length();
                }
            }
    
            // Starting from the max length as d, 
            // decrement 1 by 1 to reach the maximum common word available
            for (int d = maxLength; d > 0; d--) {
                String compare = strs[0].substring(0, d);
                boolean found = true;
                for (int i = 1; i < strs.length && found; i++) {
                    if (strs[i].indexOf(compare) != 0) {
                        found = false;
                    }
                }
                if (found)
                    return compare;
            }
            
            return "";
        }
    }

  • 0
    H

    why your code is fast than mine?

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }
        int l = strs[0].length();
        char[] firstStr = strs[0].toCharArray();
        for (int i = 1; i < strs.length; i++) {
            int sl = strs[i].length();
            if (sl < l) {
                l = sl;
            }
            for (int j = 0; j < l; j++) {
                if (strs[i].charAt(j) != firstStr[j]) {
                    l = j;
                    break;
                }
            }
        }
        return strs[0].substring(0, l);
    }
    

Log in to reply
 

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