💬 Info
Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
s
contains English letters (upper-case and lower-case), digits, and spaces ' '
.s
.풀이 시간 : 24분
trim()
, split()
사용\\s+
\\s
: 공백 문자+
: 하나 이상의 연속된 공백 의미trim()
사용)class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder answer = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
answer.append(words[i]).append(" ");
}
return answer.toString().trim();
}
}