forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReformat The String.java
48 lines (36 loc) · 1.21 KB
/
Reformat The String.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
class Solution {
public String reformat(String s) {
List<Character> ch = new ArrayList<>();
List<Character> d = new ArrayList<>();
for(char c : s.toCharArray()){
if(c >= 'a' && c <= 'z')ch.add(c);
else d.add(c);
}
if(Math.abs(d.size() - ch.size()) > 1) return "";
StringBuilder str = new StringBuilder();
for(int i = 0; i < s.length(); i++){
if(!ch.isEmpty() || !d.isEmpty()){
if(ch.size() > d.size())
str.append(appender(ch,d));
else
str.append(appender(d,ch));
}
else{
break;
}
}
return new String(str);
}
public String appender(List<Character> first,List<Character> second){
StringBuilder str = new StringBuilder();
if(!first.isEmpty()){
str.append(first.get(0));
first.remove(0);
}
if(!second.isEmpty()){
str.append(second.get(0));
second.remove(0);
}
return new String(str);
}
}