-
Notifications
You must be signed in to change notification settings - Fork 0
/
IncreasingDecreasingString.java
57 lines (49 loc) · 1.4 KB
/
IncreasingDecreasingString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package string;
import utils.LeetCode;
import utils.Level;
@LeetCode(
no=1370,
title = "Increasing Decreasing String",
level = Level.EASY,
url = "Increasing Decreasing String"
)
public class IncreasingDecreasingString {
public String sortString(String s) {
int []freq = new int[26];
StringBuffer sb= new StringBuffer();
for(int c:s.toCharArray()){
freq[c-'a']++;
}
boolean allUsed=false;
boolean isIncreasing=true;
while(!allUsed){
int zeroCount=0;
if(isIncreasing){
for(int i=0;i<freq.length;i++){
if(freq[i]!=0){
sb.append((char)(i+'a'));
freq[i]--;
}
if(freq[i]==0)
zeroCount++;
}
}
if(!isIncreasing){
for(int i=freq.length-1;i>=0;i--){
if(freq[i]!=0){
sb.append((char)(i+'a'));
freq[i]--;
}
if(freq[i]==0)
zeroCount++;
}
}
if(zeroCount==26){
allUsed=true;
}
isIncreasing=!isIncreasing;
}
// System.out.println(sb.toString());
return sb.toString();
}
}