Java는 split 정규식으로 되기 때문에 "\\s+"
로 split하면 사이의 공백이 몇개든 상관없이 나눌 수 있다.
그럼 배열 역순으로 공백 추가해주면서 StringBuilder에 더하면 끝난다.
공백으로 시작하면 배열에 공백 들어있을 수도 있으므로 trim()해준다.
class Solution {
public String reverseWords(String s) {
String[] words = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i=words.length-1; i>=0; i--) {
sb.append(words[i]);
if (i != 0) {
sb.append(" ");
}
}
return sb.toString().trim();
}
}
아니면 다른 방법으로는
뒤에서부터 공백이 아닌것을 탐색하면서 이것을 endIndex로 잡고, 또 여기서부터 공백이 아닌 것을 찾아 startIndex로 잡아서 substring 후 StringBuilder에 넣는 방법도 있다.
아래는 솔루션에서 긁어옴
class Solution {
public String reverseWords(String s) {
StringBuilder res = new StringBuilder();
int startIndex = s.length() - 1;
while(startIndex >= 0){
while(startIndex >=0 && s.charAt(startIndex) == ' ' ){ // skip spaces from behind
startIndex--;
}
if(startIndex< 0){ // Edge case: skip the spaces at the start of the word
break;
}
int endIndex = startIndex;
while(startIndex>= 0 && s.charAt(startIndex) != ' '){
startIndex--;
}
if(res.length() == 0){
res.append(s.substring(startIndex + 1, endIndex + 1));
}else{
res.append(' ');
res.append(s.substring(startIndex +1 , endIndex + 1));
}
}
return res.toString();
}
}