LeetCode 358. Rearrange String k Distance Apart

1: First thought: brute force. Get all the permutations and check permutations one by one.

/*
  Given a non-empty str and an integer k, rearrange the string such that the same
  characters are at least distance k from each other.
  all input strings are given in lowercase letters. If it is not possible to rearrange
  the string, return an empty string "".
  For example
  str = "aabbcc", k = 3, return "abcabc"
  str = "aaabc", k = 3, return ""
  str = "aaadbbcc", k = 2, return "abacabcd", another possible "abcabcda"
*/

#include <string>
#include <iostream>
#include <unordered_map>
using namespace std;

// first thought, to get the permutation of the string and check validation.
// once we found one, we can say that there is one.
bool checkValid(string str, int k) {
  unordered_map<char, int> charDistance;
  for(int i = 0; i < str.size(); ++i) {
    if(charDistance.find(str[i]) == charDistance.end()) {
      charDistance[str[i]] = i;
    } else {
      if(i - charDistance[str[i]] >= k) charDistance[str[i]] = i;
      else return false;
    }
  }
  return true;
}

void rearrangeString(string str, int k, string path, string& target, bool& found) {
  if(found) return;
  if(str.size() == 0) {
    if(checkValid(path, k)) {
      found = true;
      target = path;
      return;
    }
  }
  for(int i = 0; i < str.size(); ++i) {
    string remaining = str.substr(0, i) + str.substr(i + 1);
    rearrangeString(remaining, k, path + str[i], target, found);
  }
}

string rearrangeString(string str, int k) {
  string target = "";
  string path = "";
  bool found = false;
  rearrangeString(str, k, path, target, found);
  return target;
}

int main(void) {
  cout << rearrangeString("aaabc", 3) << endl;
}

Second Method:

// second version, using heap and greedy.
string rearrangeString(string str, int k) {
  int len = str.size();
  unordered_map<char, int> charToCount;
  for(int i = 0; i < str.size(); ++i) {
    charToCount[str[i]]++;
  }
  priority_queue< pair<int, char> > maxHeap;
  for(auto it = charToCount.begin(); it != charToCount.end(); ++it) {
    maxHeap.push({it->second, it->first});
  }
  string res;
  while(!maxHeap.empty()) {
    vector< pair<int, char> > v;
    int cnt = min(k, len); // get the minimum length.
    for(int i = 0; i < cnt; ++i) {
      if(maxHeap.empty()) return ""; // if left different chars numbers are smaller than the required, return false.
      auto q = maxHeap.top();
      maxHeap.pop();
      res.push_back(q.second);
      if(--q.first > 0) v.push_back(t);
      len--;
    }
    for(auto a : v) maxHeap.push(a);
  }
  return res;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值