Given a non-empty string s 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 "".

Example 1:

Input: s = "aabbcc", k = 3
Output: "abcabc"
Explanation: The same letters are at least distance 3 from each other.

Example 2:

Input: s = "aaabc", k = 3
Output: ""
Explanation: It is not possible to rearrange the string.

Example 3:

Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least distance 2 from each other.

Runtime: 8 ms, faster than 99.59% of C++ online submissions for Rearrange String k Distance Apart.

和之前的一道题很类似

bool cmp(pair<char, int> a, pair<char, int> b) {
if (a.second != b.second) return a.second < b.second;
return a.first < b.first;
} class Solution {
public:
string rearrangeString(string s, int k) {
vector<pair<char, int>> map(, pair<char,int>('a',));
for (int i = ; i < s.size(); i++) {
int idx = s[i] - 'a';
if (map[idx].second == ) {
map[idx].first = s[i];
map[idx].second = ;
}
else {
map[idx].second++;
}
}
sort(map.begin(), map.end(), cmp);
//for(auto m : map) cout << m.first << m.second << endl;
int idx = map.size() - ;
int maxrep = map[idx].second;
string ret = "";
while (idx >= && map[idx].second == maxrep) {
string tmpstr = string(,map[idx].first);
ret += tmpstr;
idx--;
}
//cout << ret << endl;
vector<string> retvec(map.back().second - , ret);
int cnt = ;
while (idx >= && map[idx].second != ) {
int tmp = idx;
string tmpstr =string(, map[tmp].first);
while (map[tmp].second != ) {
retvec[cnt] += tmpstr;
map[tmp].second--;
cnt++;
if(cnt >= retvec.size()) cnt = ;
}
idx--;
}
for (auto s : retvec) {
if (s.size() < k) return "";
}
string finalret = "";
for (auto s : retvec) finalret += s;
finalret += ret;
return finalret;
}
};

最新文章

  1. 【leetcode】Fraction to Recurring Decimal
  2. 推荐一篇 OAuth 2.0 必读文章
  3. numpy.concatenate
  4. 最后关于Pipeline完整的图如下:
  5. 直接把数据库中的数据保存在CSV文件中
  6. Python基础学习笔记(十)日期Calendar和时间Timer
  7. Linux操作系统下的Sudo命令
  8. android 使用系统照相程序照相并存储、显示在界面上
  9. 基于maven进行spring 和mybatis的整合(Myeclpise)
  10. MVC中实现多按钮提交(转)
  11. activiti processEngineLifecycleListener使用
  12. Exp5 MSF基础应用 20164314
  13. [JavaScript] 前端模块加载简单实现(require)
  14. javaScript系列 [02]-javaScript对象探析
  15. Object.keys(),Object.values() 用法
  16. windows 网卡配置的设置命令
  17. react-navigation,StackNavigator,TabNavigator 导航使用
  18. bzoj千题计划279:bzoj4591: [Shoi2015]超能粒子炮&#183;改
  19. bestcoder 48# wyh2000 and a string problem (水题)
  20. Chapter 4 需求工程

热门文章

  1. 【转】bitbake 笔记
  2. Ubuntu 18.04 手动升级内核
  3. BPR贝叶斯个性化排序算法
  4. 记录一下linux下两个工具和一个伪代码转换流程图工具
  5. Bridge 桥梁模式
  6. web页面ios浏览器img图片的坑
  7. 第六章 组件 61 动画-小球动画flag标识符的作用分析
  8. JavaScript中foreach、map函数
  9. c++关于字符串的读入和截取
  10. Java-DatabaseConnectionPool工具类