[M] 151. Reverse Words in a String

YJ·2025년 3월 9일

leetcode

목록 보기
14/100

https://leetcode.com/problems/reverse-words-in-a-string

문제

str 주어지면, whitespace 기준으로 나눠서 역순 배치
ex) the sky is blue -> blue is sky the

답안

public String reverseWords(String s) {
	s = s.trim();
	s = s.trim().replaceAll(" +", " ");
	String[] words = s.split(" ");
    String ans = "";
    for (int i = words.length - 1; i >= 0; i--) {
		ans += words[i] + " ";
	}
	return ans.trim(); // 마지막 빈 칸 없애주는 역할
}

trim() 하고, split() 해서 역순 배치

메모

String[] str = s.trim().split("\\s+"); 이런 식으로 한 번에 간단하게 trim 하는 것도 가능하다.

단, 이 문제는 trim() 과 split() 내장 함수를 쓰지 않고 Two Pointers 를 사용하는 것이 의도인 듯하니 다음에 풀 때는 Two Pointers 로 풀어보기

profile
Hello

0개의 댓글