문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
주어진 문자열 text는 여러 개의 단어가 공백으로 나눠져있다. 각 단어는 하나 이상의 영어 소문자로 구성되고, 적어도 하나의 공백으로 구분된다. text는 적어도 하나의 단어가 포함되는 것을 보장한다.
인접한 두 단어 사이의 공백 개수가 동일하고, 개수가 최대가 되도록 공백을 재배열해라. 모든 공백을 동일하게 재배열할 수 없는 경우, 남는 공백은 문자열 끝에 배치해라. 반환되는 문자열의 길이는 text와 같아야 한다.
공백을 재배열한 문자를 반환해라.
#1
Input: text = " this is a sentence "
Output: "this is a sentence"
Explanation: 9개의 공백과 4개의 단어가 있다. 단어 사이에 9개의 공백을 9 / (4 - 1) = 3의 공백으로 나눌 수 있다.
#2
Input: text = " practice makes perfect"
Output: "practice makes perfect "
Explanation: 7개의 공백과 3개의 단어가 있다. 7 / (3 - 1) = 3 공백과 1개의 추가 공백이 있다. 추가 공백을 문자열 끝에 위치한다.
class Solution {
public String reorderSpaces(String text) {
int spaces = 0;
for(char c: text.toCharArray()) {
if (c == ' ') {
spaces++;
}
}
List<String> words = splitInWords(text);
int trailingSpaces = 0;
StringBuilder result = new StringBuilder();
if (words.size() == 1) {
trailingSpaces = spaces;
result.append(words.get(0));
} else {
int equalSpaces = spaces / (words.size() - 1);
trailingSpaces = spaces - equalSpaces * (words.size() - 1);
StringBuilder spacesString = new StringBuilder();
for(int i=0; i<equalSpaces; i++) {
spacesString.append(' ');
}
for(int i=0; i < words.size(); i++) {
if (i > 0) {
result.append(spacesString.toString());
}
result.append(words.get(i));
}
}
while(trailingSpaces > 0) {
result.append(' ');
trailingSpaces--;
}
return result.toString();
}
private List<String> splitInWords(String text) {
List<String> words = new ArrayList<>();
int index = 0;
while(text.charAt(index) == ' ') {
index++;
}
StringBuilder word = new StringBuilder();
while(index < text.length()) {
if (text.charAt(index) != ' ') {
word.append(text.charAt(index));
} else {
if (word.length() > 0) {
words.add(word.toString());
word = new StringBuilder();
}
}
index++;
}
if (word.length() > 0) {
words.add(word.toString());
}
return words;
}
}