Leetcode 1370. Increasing Decreasing String

Leetcode 1370. Increasing Decreasing String

题目链接: Increasing Decreasing String

难度:easy

题目大意:

按照题目要求对字符串进行排序。

思路:

1、统计字符串中各个字母的个数,用一个int类型的数组count[]来表示。count[0]~count[25]分别表示字母a-z出现的次数。大佬们用树状图来统计。
2、对数组进行扫描,如果count[i]大于零,输出对应的字母,将count[i]减一。
3、count[i]全部为零时,返回结果。

代码

class Solution {
    public String sortString(String s) {
        int count[]=new int[26];//a[0]~a[25]分别表示a~z的数量
        for(int i=0;i<s.length();i++){
            int j=s.charAt(i)-'a';
            count[j]++;
        }
        int sum=s.length();
        StringBuilder res=new StringBuilder();
        
        while(res.length()<sum){
            for(int j=0;j<26;j++){
                if(count[j]>0){
                    res.append((char)(j+'a'));
                    count[j]--;
                }
            }
            
            
            for(int j=25;j>=0;j--){
                if(count[j]>0){
                    res.append((char)(j+'a'));
                    count[j]--;
                }
            }            
        }
        return res.toString();
    }
}

备注

String中的对象是不可变的,当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。
Java中StringBuilder的用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值