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

[LC] 767. Reorganize String

时间:2020-01-31 14:18:49      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:string   priority   aaa   note   key   value   toc   entry   empty   

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result.  If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].
class Solution {
    public String reorganizeString(String S) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : S.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (b.getValue() - a.getValue()));
        for (Map.Entry<Character, Integer> entry: map.entrySet()) {
            pq.offer(entry);
        }
        
        Map.Entry<Character, Integer> prev = null;
        StringBuilder sb = new StringBuilder();
        while (!pq.isEmpty()) {
            Map.Entry<Character, Integer> cur = pq.poll();
            sb.append(cur.getKey());
            cur.setValue(cur.getValue() - 1);
            
            if (prev != null) {
                pq.offer(prev);
            }
            if (cur.getValue() > 0) {
                prev = cur;
            } else {
                prev = null;
            }
        }
        return sb.length() == S.length() ? sb.toString() : "";
    }
}

 

[LC] 767. Reorganize String

标签:string   priority   aaa   note   key   value   toc   entry   empty   

原文地址:https://www.cnblogs.com/xuanlu/p/12245020.html

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