Java Code, construct a comparator for string

  • 0

    I find there is not enough submitting for this problem. So I paste my code here.
    On my opinion, to solve this problem we need actually to define a series of rules for compare to strings in this situation, which is(assume we wanna to compare String s1 and String s2):

    when s1.length == s2.length
    compare them as normal "string compare", like "321" > "123";
    when s1.length > s2.length
    1. first we compare public length of them as normal "string compare", like for "1234" and "11", first we compare "12"(substring of "1234") and "11", if they are not equal, we could return it.
    2. if they are equal, then we should compare the left substrings of s1 to s2 recursively, like "6761" and "67", because "67" in "6761"(s1) is equal to "67"(s2), so we compare "61" in "6761"(s1) to "67"(s2) recursively.

    Then we sort this array of strings and construct the largest num in desc order.

     public String largestNumber(int[] num) {
                String[] s = new String[num.length];
                for (int i = 0; i < s.length; i++) {
                    s[i] = num[i] + "";
                Arrays.sort(s, com);
                String ret = "";
                for (int i = s.length - 1; i >= 0; i--) {
                    ret += s[i];
                if (ret.charAt(0) == '0')
                    return "0";
                return ret;
            private Comparator<String> com = new Comparator<String>(){
                public int compare(String s1, String s2){
                    if (s1.length() == s2.length()) {
                        return s1.compareTo(s2);
                    int pub = Math.min(s1.length(), s2.length());
                    int pubCom = s1.substring(0,pub).compareTo(s2.substring(0,pub));
                    if (pubCom == 0){
                        if (s1.length() > pub){
                            return compare(s1.substring(pub),s2);
                        } else {
                            return compare(s2.substring(pub),s1) * (-1);
                    }else {
                        return pubCom;

  • 3

    you can simply compare s1+s2 and s2+s1

Log in to reply

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