leetcode 1370. Increasing Decreasing String

本文介绍了一种基于计数排序原理的字符串排序算法实现。通过遍历输入字符串,统计每个字符出现的次数,然后按顺序和逆序交替拼接字符,形成最终排序后的字符串。此方法适用于小范围字符集的排序,如仅包含小写字母的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
按题意实现就可

class Solution {
    public String sortString(String s) {
        char[] arr = s.toCharArray();
        int[] count = new int[26];
        for(int chr:arr){
            count[chr-'a']++;
        }
        String s1 = "";
        int index = s.length();
        while(index>0){
            for(int i=0;i<26;i++){
                if(count[i]>0){
                    s1 += (char)('a'+i);
                    count[i]--;
                    index--;
                }
            }
            for(int j=25;j>=0;j--){
                if(count[j]>0){
                    s1 += (char)('a'+j);
                    count[j]--;
                    index--;
                }
            }
        }
        return s1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值