Java ------ We Love Clear Code!


  • 24
    J
    public String longestCommonPrefix(String[] strs) {
        if (strs == null) return null;
        if (strs.length == 0) return "";
        
        Arrays.sort(strs);
        char[] first = strs[0].toCharArray();
        char[] last  = strs[strs.length - 1].toCharArray();
         
        int i = 0, len = Math.min(first.length, last.length);
        while (i < len && first[i] == last[i]) i++;
        return strs[0].substring(0, i);
    }

  • 2
    M

    nice code! You do not need take the min of the length of first and last, since after sorting the array first.length is guaranteed to be no more than last.length.


  • 2
    G

    @mustangigem try sorting {"abcd", "az"} and you will find that length of first element is longer than the length of last element


  • 2

    I think this code will spend more Runtime and more space even though the code looks clear.


  • 0
    H

    Quiet a nice one.Got it!


Log in to reply
 

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