• leetcode 767. Reorganize String


    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

    If possible, output any possible result. If not possible, return the empty string.

    Example 1:
    
    Input: S = "aab"
    Output: "aba"
    Example 2:
    
    Input: S = "aaab"
    Output: ""
    

    题目大意给出一个字符串,重新排列字符串使得相邻的两个字母不相同,并输出这个重新排列后的字符串,如果没有符合条件的就返回空字符串。
    思路:贪心,每次把数量最多的2个字母配对,添加到构造的字符串中。这样能保证后面构造时的成功性最高。用优先队列实现。

    class Solution {
    public:
        string reorganizeString(string S) {
            map<char, int> mp;
            for (int i = 0; i < S.size(); ++i) {
                mp[S[i]]++;
            }
            priority_queue< pair<int, char> > q;
            for (auto x : mp) {
                q.push({x.second, x.first});
            }
            string s = "";
            while (!q.empty()) {
                pair<int, char> u, v;
                u = q.top();
                q.pop();
                if (u.first > 0) {
                    s += u.second;
                    --u.first;
                    if (q.empty()) break;
                    v = q.top();
                    q.pop();
                    if (v.first > 0) {
                        s += v.second;
                        --v.first;
                        q.push(v);
                    } else {
                        break;
                    }
                    q.push(u);
                } 
            }
            if (s.size() != S.size()) return "";
            return s;
        }
    };
    
  • 相关阅读:
    dubbo
    maven
    vue
    SSM框架整合
    MyBatis数据表注解开发
    MyBatis多表操作xml方式
    MyBatis映射配置文件
    Mybatis核心配置文件,传统开发和代理开发(主流)
    SpringMVC高级
    SpringMVC基础
  • 原文地址:https://www.cnblogs.com/pk28/p/8483115.html
Copyright © 2020-2023  润新知