1. 程式人生 > >LC 358. Rearrange String k Distance Apart

LC 358. Rearrange String k Distance Apart

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(26, pair<char,int>('a',0)); for (int i = 0; i < s.size(); i++) { int idx = s[i] - 'a'; if (map[idx].second == 0) { map[idx].first = s[i]; map[idx].second = 1; } else { map[idx].second++; } } sort(map.begin(), map.end(), cmp); //for(auto m : map) cout << m.first << m.second << endl; int idx = map.size() - 1; int maxrep = map[idx].second; string ret = ""; while (idx >= 0 && map[idx].second == maxrep) { string tmpstr = string(1,map[idx].first); ret += tmpstr; idx--; } //cout << ret << endl; vector<string> retvec(map.back().second - 1, ret); int cnt = 0; while (idx >= 0 && map[idx].second != 0) { int tmp = idx; string tmpstr =string(1, map[tmp].first); while (map[tmp].second != 0) { retvec[cnt] += tmpstr; map[tmp].second--; cnt++; if(cnt >= retvec.size()) cnt = 0; } idx--; } for (auto s : retvec) { if (s.size() < k) return ""; } string finalret = ""; for (auto s : retvec) finalret += s; finalret += ret; return finalret; } };