-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReformatTheString.java
45 lines (39 loc) · 1.34 KB
/
ReformatTheString.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
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/reformat-the-string/
public class ReformatTheString {
private final String input;
public ReformatTheString(String input) {
this.input = input;
}
public String solution() {
List<Character> letters = new ArrayList<>();
List<Character> digits = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
digits.add(c);
} else {
letters.add(c);
}
}
int diff = letters.size() - digits.size();
if (diff == -1 || diff == 0 || diff == 1) {
List<Character> max = letters.size() > digits.size() ? letters : digits;
List<Character> min = max == letters ? digits : letters;
StringBuilder result = new StringBuilder();
int maxP = 0;
int minP = 0;
while (maxP < max.size() && minP < min.size()) {
result.append(max.get(maxP++));
result.append(min.get(minP++));
}
if (diff != 0) {
result.append(max.get(maxP));
}
return result.toString();
}
return "";
}
}