문제
입력 문자열 s가 주어졌을 때, 단어의 순서를 역순으로 정렬합니다.
단어는 공백이 아닌 문자들의 시퀀스로 정의됩니다. s에 포함된 단어들은 최소 하나의 공백으로 구분됩니다.
단어들을 하나의 공백으로 연결된 역순 문자열을 반환합니다.
s는 앞뒤 공백을 포함하거나 두 단어 사이에 여러 개의 공백을 포함할 수 있습니다. 반환된 문자열은 단어들을 구분하는 공백을 하나만 포함해야 합니다. 추가 공백은 포함하지 마십시오.
예시
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
아이디어
public String reverseWords(String s) {
String[] origin = s.trim().split(" ");
String result = "";
for (int i = origin.length - 1; i >= 0; i--) {
if (origin[i].isEmpty()) {
continue;
}
if (i == 0) {
result += origin[i];
} else {
result += origin[i] + " ";
}
}
return result;
}
1차 결과

'💻알고리즘' 카테고리의 다른 글
| [LeetCode] 392. Is Subsequence (0) | 2025.08.25 |
|---|---|
| [LeetCode] 238. Product of Array Except Self (4) | 2025.08.25 |
| [LeetCode] 345. Reverse Vowels of a String (0) | 2025.08.25 |
| [LeetCode] 605. Can Place Flowers (0) | 2025.08.25 |
| [LeetCode] 1431. Kids With the Greatest Number of Candies (0) | 2025.08.25 |