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的用法