码迷,mamicode.com
首页 > 其他好文 > 详细

sort-characters-by-frequency

时间:2016-11-04 23:38:30      阅读:274      评论:0      收藏:0      [点我收藏+]

标签: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();

    }
}

 

sort-characters-by-frequency

标签:etc   list   cep   get   ack   array   ring   tco   err   

原文地址:http://www.cnblogs.com/charlesblc/p/6031645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!