LeetCode 767. Reorganize String - 优先级队列(Priority Queue)系列题7

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return "" if not possible.

Example 1:

Input: s = "aab"
Output: "aba"

Example 2:

Input: s = "aaab"
Output: ""

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

题目给定一个字符串,要求重排字符串里的字符使得任意两个相邻的字符都是不同的字符,返回重排后的字符串,如果无法做到就返回一个空字符串。

很明显,如果有某一个字符的出现频率超过总个数的一半(总个数n为偶数时一半是n//2, 为奇数时一半规定为n//2 + 1, 统一起来就是频率大于(n + 1) // 2),那么不管怎么重排都至少有一对相邻的字符是相同的。因此,首先需要保证所有字符的个数都要不超过总个数的一半(<&

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值