排序LeetCode 767 Reorganize String

LeetCode 767

Reorganize String

  • Problem Description:
    对字符串中的字符顺序进行调整,如果能够使相邻字符不相同,返回调整后的任一满足字符串,否则返回空字符串。
    具体的题目信息:
    https://leetcode.com/problems/reorganize-string/description/
  • Example:
    这里写图片描述
  • Solution:
    • 解题思路:
      (1)遍历字符串,记录每一字符出现的次数,用map容器存储
      (2)为了对map中元素按照value值排序,引入vector,自定义比较函数,使得出现次数多的字符排在数组前方
      (3)进行是否能通过调整使相邻字符不相同的判断:if (v[0].second>ceil(S.length()/2.0))
      (4)对于可以调整的情况:先把出现次数最多的字符插入输出字符串res中,对剩下的字符依次从尾部插入【这部分插入我还不太理解 QAQ】
    • 编程实现:
class Solution {
public:
//定义比较函数,按照map中value值大小从大到小排序
    static bool cmp(pair<char, int>& p1, pair<char, int>& p2) {
        return p1.second>p2.second;
    }
    string reorganizeString(string S) {
        if (S.length() == 0||S.length() == 1) return S;
        map<char, int> t;
        //统计每一字符出现的次数
        for (int i = 0; i < S.length(); i++) {
            t[S[i]]++;
        }
        //将map容器中东西放到vector容器中方便排序
        vector<pair<char, int>> v(t.begin(), t.end());
        sort(v.begin(), v.end(), cmp);
        string res = "";
        char temp;
        int nextpos;
        if (v[0].second>ceil(S.length()/2.0)) return res;
        for (int i = 0; i < v.size(); i++) {
            if (res.length() == 0) {
                while(v[i].second--) {
                    res.insert(res.begin(), v[i].first);
                }
                //从字符串的尾部进行插入操作,nextpos指向插入的位置
                nextpos = res.size()-1;
            } else {
               while(v[i].second--) {
                   res.insert(res.begin()+nextpos, v[i].first);
                   nextpos = (nextpos-1)%res.size();
               } 
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/shey666/article/details/80752514