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