[LeetCode / Medium] 151. Reverse Words in a String (Java)

이하얀·2025년 2월 8일
0

📙 LeetCode

목록 보기
8/13

💬 Info



Problem

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.



Example

예시 1

  • Input: s = "the sky is blue"
  • Output: "blue is sky the"

예시 2

  • Input: s = " hello world "
  • Output: "world hello"
  • Explanation: Your reversed string should not contain leading or trailing spaces.

예시 3

  • Input: s = "a good example"
  • Output: "example good a"
  • Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints

  • 1 <= s.length <= 10410^4
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
    There is at least one word in s.


문제 이해

  • 단어 뒤집기: 영단어로만 이뤄진 단어를 출력해야하는 데에 유의점이 있음!


알고리즘

풀이 시간 : 24분

  • 공백 제거, 단어 분리
    • trim(), split() 사용
    • \\s+
      • \\s : 공백 문자
      • + : 하나 이상의 연속된 공백 의미
  • 단어 역순 추가
    • StringBuilder 단어 추가
  • 마지막 공백 제거 & 반환(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();
    }
}


결과


profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글