zoukankan      html  css  js  c++  java
  • 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: ""
    

    Note:

    • S will consist of lowercase letters and have length in range [1, 500].

    Approach #1 Sort by count:

    class Solution {
    public:
        string reorganizeString(string S) {
            int len = S.length();
            vector<int> count(26, 0);
            string ans = S;
            for (auto s : S) count[s-'a'] += 100;
            for (int i = 0; i < 26; ++i) count[i] += i;
            sort(count.begin(), count.end());
            int start = 1;
            int mid = (len + 1) / 2;
            for (int i = 0; i < 26; ++i) {
                int times = count[i] / 100;
                char c = 'a' + (count[i] % 100);
                if (times > mid) return "";
                for (int j = 0; j < times; ++j) {
                    if (start >= len) start = 0;
                    ans[start] = c;
                    start += 2;
                }
            }
            //ans += '';
            return ans;
        }
    };
    
    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reorganize String.
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    nodejs之express路由与动态路由
    nodejs之mongodb操作
    nodejs之路由
    nodejs之简单应用与运行
    nodejs之fs 模块
    nodejs 之简单web服务器
    C++之结构体struct
    STL之stack
    【剑指offer】05替换空格,C++实现
    【剑指offer】04A二维数组中的查找,C++实现
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9884224.html
Copyright © 2011-2022 走看看