Reorganize String

[leetcode]Reorganize String

链接:https://leetcode.com/problems/reorganize-string/description/

Question

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].

Solution

class Solution {
public:
#define print(A) cout << #A << ": "<< A << endl;
  struct node {
    char character;
    int count;
    node(char c = ' ', int cnt = -1): character(c), count(cnt) {}
    bool operator<(const node& another) const {
      return count < another.count;
    }
  };
  // 维护一个priority_queue,按照次数从大到小排序。然后每次取出最大的两个字母,将其次数减一重新放入优先队列,一直到优先队列为空。
  string reorganizeString(string S) {
    priority_queue<node> pq;
    map<char, int> mp;
    for (int i = 0; i < S.size(); i++) {
      if (mp.find(S[i]) == mp.end()) {
        mp[S[i]] = 1;
      } else {
        mp[S[i]]++;
        if (mp[S[i]] > (S.size()+1)/2 ) return "";
      }
    }
    for (auto iter = mp.begin(); iter != mp.end(); iter++) {
      pq.push(node(iter->first, iter->second));
    }
    string res;
    while (pq.size() > 1) {
      node first = pq.top(); pq.pop();
      node second = pq.top(); pq.pop();
      res.push_back(first.character);
      res.push_back(second.character);
      first.count--;
      if (first.count > 0) {
        pq.push(node(first.character, first.count));
      }
      second.count--;
      if (second.count > 0) {
        pq.push(node(second.character, second.count));
      }
    }
    if (pq.size() == 1)
      res += pq.top().character;
    return res;
  }
};

思路:这道题很机智,思想就是你不是说要不能相邻嘛,那我尽量相邻咯~方法就是挑当前最多的两个字符相邻,然后两个字符次数-1之后重复上述操作。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值