코린이의 소소한 공부노트

[LeetCode/Medium] 151. Reverse Words in a String 본문

코딩테스트 풀이/JAVA

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

무지맘 2023. 1. 20. 22:19

1. Input

1) String s

 

2. Output

1) s의 단어들을 역순으로 나열한 문자열 반환

 

3. Constraint

1) 1 <= s.length <= 104

2) s는 영어 대소문자, 숫자, 공백 문자로 이루어져 있다.

3) s에는 최소 1개의 단어가 있다.

4) 단어는 공백 문자로 구분되어 있는데, 단어 사이에 여러 개의 공백 문자가 들어있을 수 있다. 반환할 때는 단어 사이에 반드시 1개의 공백 문자가 있어야 한다.

 

4. Example

Input: s = "a good example" -> Output: "example good a"

Input: s = " hello world " -> Output: "world hello"

 

5. Code

1) 첫 코드(2023/01/20)

String[] words = s.trim().split("[ ]+");
for(int i=words.length-2 ; i>=0 ; i--){
    words[words.length-1] += " " + words[i];
}
return words[words.length-1];