-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecordSpaces.java
More file actions
43 lines (39 loc) · 1.12 KB
/
RecordSpaces.java
File metadata and controls
43 lines (39 loc) · 1.12 KB
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
import java.util.ArrayList;
import java.util.Arrays;
/**
* 1592 重新排列单词间的空格
*/
public class RecordSpaces {
public String reorderSpaces(String text) {
char[] res = new char[text.length()];
Arrays.fill(res, ' ');
ArrayList<ArrayList<Character>> list = new ArrayList<>();
int space = 0;
for(int i=0; i<text.length();){
if(text.charAt(i)!=' ') {
ArrayList<Character> temp = new ArrayList<>();
while (i < text.length() && text.charAt(i) != ' ') {
temp.add(text.charAt(i));
i++;
}
list.add(temp);
}else{
i++;
space++;
}
}
if(list.size()>1){
space = space/(list.size()-1);
}
for(int i=0, index=0; i<list.size(); i++){
for(char c: list.get(i)) {
res[index] = c;
index++;
}
if(list.size()-i>1){
index = index + space;
}
}
return new String(res);
}
}