zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 767 重构字符串(ASCII的转换)

    767. 重构字符串

    给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

    若可行,输出任意可行的结果。若不可行,返回空字符串。

    示例 1:

    输入: S = “aab”
    输出: “aba”
    示例 2:

    输入: S = “aaab”
    输出: “”
    注意:

    S 只包含小写字母并且长度在[1, 500]区间内。

    class Solution {
         public String reorganizeString(String S) {
            if (S == null || S.length() == 0) {
                return "";
            }
    
            int length = S.length();
            int[] counts = new int[26];
            for (char c : S.toCharArray()) {
                counts[c - 'a'] += 100;
            }
    
            for (int i = 0; i < 26; ++i) {
                counts[i] += i;
            }
            Arrays.sort(counts);
            char[] result = new char[length];
            int t = 1;
            for (int code : counts) {
                int ct = code / 100;
                char ch = (char) ('a' + (code % 100));
                if (ct > (length + 1) / 2) {
                    return "";
                }
                for (int i = 0; i < ct; ++i) {
                    if (t >= length) {
                        t = 0;
                    }
                    result[t] = ch;
                    t += 2;
                }
            }
    
            return String.valueOf(result);
        }
    }
    
  • 相关阅读:
    pandas 和反射联合使用
    反射
    获取Cookie 遇到的问题
    接口自动化之 问题
    接口自动化之 数据库操作
    logging日志模块
    数据驱动 --ddt
    logging--日志打印模块
    APP专项测试5 --PFS
    Monkey 参数
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074653.html
Copyright © 2011-2022 走看看