Implementation without directly compare two strings


  • 0
    L
    public class Solution {
        class myComparator implements Comparator<String> {
            @Override
            public int compare(String o1, String o2) {
                if(o1.equals(o2)) return 0;
                int index = 0;
                while(index < o1.length() && index < o2.length()) {
                    if(o2.charAt(index) > o1.charAt(index)) return 1;
                    if(o2.charAt(index) < o1.charAt(index)) return -1;
                    index++;
                }
                while(index < o2.length()) {
                    if(o2.charAt(index) > o1.charAt(index % o1.length())) return 1;
                    if(o2.charAt(index) < o1.charAt(index % o1.length())) return -1;
                    index++;
                }
                while(index < o1.length()) {
                    if(o1.charAt(index) > o2.charAt(index % o2.length())) return -1;
                    if(o1.charAt(index) < o2.charAt(index % o2.length())) return 1;
                    index++;
                }
                if(o2.length() > o1.length()) {
                    return o2.charAt(index - 1) > o2.charAt(index - 2) ? 1 : -1;
                }
                return o1.charAt(index - 1) > o1.charAt(index - 2) ? -1 : 1;
            }
        }
        
        public String largestNumber(int[] nums) {
            StringBuilder sb = new StringBuilder();
            PriorityQueue<String> maxHeap = new PriorityQueue<>(nums.length, new myComparator());
            for(int num: nums) maxHeap.offer(String.valueOf(num));
            while(!maxHeap.isEmpty()) sb.append(maxHeap.poll());
            if(sb.charAt(0) == '0') return sb.toString().substring(0, 1);
            return sb.toString();
        }
    }
    

Log in to reply
 

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