My Java solution with a little bit different comparator


  • 2
    L
    public String largestNumber(int[] num) {
        
        if (num==null || num.length==0) return "";
        
        String[] strs = new String[num.length];
        
        for (int i=0; i<strs.length; i++) {
            strs[i] = String.valueOf(num[i]);
        }
        
        Arrays.sort(strs,strCmp);
        
        StringBuilder buf = new StringBuilder();
        
        for (int i=0; i<strs.length; i++) {
            buf.append(strs[i]);
        }
        
        int startNonZero = 0;
        
        while(startNonZero<buf.length() && buf.charAt(startNonZero)=='0') {
            startNonZero++;
        }
        if (startNonZero==buf.length()) return "0";
        
        return buf.substring(startNonZero,buf.length());
        
    }
    
    private static Comparator<String> strCmp = new Comparator<String>() {
      
      public int compare(String s1, String s2) {
          
          for (int i=0;i<s1.length()+s2.length();i++) {
              char c1 = s1.charAt(i%s1.length());
              char c2 = s2.charAt(i%s2.length());
              if (c1!=c2) return c2-c1;
          }
          
          return 0;
          
      }  
    };

Log in to reply
 

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