标签:etc list cep get ack array ring tco err
https://leetcode.com/problems/sort-characters-by-frequency/
用了Jave Map.Entry这个数据结构,还用到了自定义的Comparator。
package com.company; import java.util.*; class Solution { class MyComparator implements Comparator { @Override public int compare(Object o1, Object o2) { Map.Entry e1 = (Map.Entry) o1; Map.Entry e2 = (Map.Entry) o2; // Reverse return (int)e2.getValue() - (int)e1.getValue(); } } public String frequencySort(String s) { Map<String, Integer> mp = new HashMap<>(); for (int i=0; i<s.length(); i++) { String key = s.substring(i, i+1); if (mp.containsKey(key)) { mp.put(key, mp.get(key)+1); } else { mp.put(key, 1); } } List<Map.Entry> lst = new ArrayList<>(mp.entrySet()); Collections.sort(lst, new MyComparator()); Iterator<Map.Entry> iter = lst.iterator(); StringBuilder sb = new StringBuilder(); while (iter.hasNext()) { Map.Entry entry = iter.next(); for (int j=0; j<(int)entry.getValue(); j++) { sb.append(entry.getKey()); } } return sb.toString(); } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!"); Solution solution = new Solution(); // Your Codec object will be instantiated and called as such: String s = "Aabb"; String ret = solution.frequencySort(s); System.out.printf("root:%s\n", ret); System.out.println(); } }
标签:etc list cep get ack array ring tco err
原文地址:http://www.cnblogs.com/charlesblc/p/6031645.html