/****************************** LeetCode 358 Rearrange String k Distance Apart ******************************/ /****************************** 思想: 1.建立map,遍历字符串,统计字符出现的次数 2.定义一个数组nextPosition[26],存储字符下次可以出现的位置 3.字符串长度的循环体 每次寻找剩下字符中,个数最多的字符,且要满足的条件是 此处的位置大于nextPosition[i] 存在这样的字符,则加入结果字符 不存在的话,则返回"",说明不存在这样的字符串 注意维护nextPosition数组 时间复杂度: n+26*n n是字符串的长度 空间复杂度 O(1) 测试用例: *******************************/ string rearrangeString(string str, int k) { map<char, int> hashmap; int size = str.size(); //建立hash表,统计每个字符出现的次数 for (int ii = 0; ii < size; ++ii) { hashmap[str[ii]] += 1; } int nextPosition[26];//存储字符下次出现的位置 memset(nextPosition, 0, sizeof(nextPosition)); string result; int count = 0;//字符串长度 for (int ii = 0; ii < size; ++ii) { //寻找剩下字符中个数最多的 char ch = '\0'; int max = 0; for (map<char, int>::iterator iter = hashmap.begin(); iter != hashmap.end(); ++iter) { if (count >= nextPosition[iter->first - 'a'] && iter->second>max) { max = iter->second; ch = iter->first; } } //判断是否找到 if (max>0 && ch != '\0') { //找到了 result += ch; hashmap[ch] -= 1; nextPosition[ch - 'a'] = count + k;//下次可以放的位置 count++; } else { return ""; } } return result; }