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 58 59 60 61
| class Solution { public String reorderSpaces(String text) { List<String> list = new ArrayList<>(); int num = 0; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == ' ') { num++; if (buffer.length() > 0) { list.add(buffer.toString()); buffer.delete(0, buffer.length()); } }else { buffer.append(text.charAt(i)); } }
if (buffer.length() > 0) { list.add(buffer.toString()); } buffer.delete(0, buffer.length());
if (num == 0) { return text; }
int k = list.size() - 1; if (k == 0) { buffer.append(list.get(0)); for (int i = 0; i < num; i++) { buffer.append(' '); } return buffer.toString(); }
int j = num / k; int r = num % k;
for (int i = 0; i < list.size(); i++) { buffer.append(list.get(i)); if (i == list.size() - 1) { continue; } for (int l = 0; l < j; l++) { buffer.append(' '); } }
for (int i = 0; i < r; i++) { buffer.append(' '); } return buffer.toString(); } }
|