0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 451. Sort Characters By Frequency

Last updated at Posted at 2022-12-03

451. Sort Characters By Frequency

難易度

Medium

アプローチ

Hashmap

class Solution {
    public String frequencySort(String s) {
        HashMap<Character, Integer> hashMap = new HashMap<>();

        for (char c : s.toCharArray()) {
            hashMap.put(c, hashMap.getOrDefault(c, 0) + 1);
        }

        return hashMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue((o1, o2) -> -o1.compareTo(o2)))
                .map(entry -> String.valueOf(entry.getKey()).repeat(entry.getValue()))
                .map(String::valueOf)
                .collect(Collectors.joining());

/*
        return hashMap.entrySet().stream()
                .sorted((o1, o2) -> o2.getValue() - o1.getValue())
                .map(obj -> String.valueOf(obj.getKey()).repeat(obj.getValue()))
                .map(String::valueOf)
                .collect(Collectors.joining());
*/
    }
}
  • こちらの回答を参照しました
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?