Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- ㅒ
- 서버설정
- baeldung
- /etc/network/interfaces
- 데비안
- iterator
- 자바편
- 페이징
- 자료구조와함께배우는알고리즘입문
- 구멍가게코딩단
- 스프링부트핵심가이드
- 선형대수
- GIT
- 네트워크 설정
- network configuration
- resttemplate
- 친절한SQL튜닝
- 리눅스
- 처음 만나는 AI수학 with Python
- d
- 목록처리
- 이터레이터
- 알파회계
- Kernighan의 C언어 프로그래밍
- 스프링 시큐리티
- 코드로배우는스프링웹프로젝트
- 티스토리 쿠키 삭제
- 코드로배우는스프링부트웹프로젝트
- 자료구조와 함께 배우는 알고리즘 입문
- 처음 만나는 AI 수학 with Python
Archives
- Today
- Total
bright jazz music
151. Reverse Words in a String 본문
https://leetcode.com/problems/reverse-words-in-a-string/?envType=study-plan-v2&envId=leetcode-75
function reverseWords(s: string): string {
// 먼저 트림하고
let trimedWords = s.trim();
// ' ' 를 기준으로 split한 뒤에
// pop 해서 스트링에 붙여서 반환
// let splitWordsArr = trimedWords.split(' ');
// 위처럼만 하면 ' ' 이런 경우 공백이 붙어버리기 때문에
// filter(w => w !== '') 이걸 써서 공백을 없애버려야 한다.
let splitWordsArr = s.trim().split(' ').filter(w => w !== '');
let result = '';
// 이렇게 하면 pope되면서 배열 길이 자체가 줄어듬. 따라서 절반만 실행됨
// for(let i = 0; i < splitWordsArr.length; i++) {
// console.log(splitWordsArr.pop());
// }
let len = splitWordsArr.length;
// for문으로 하자면 이렇게
// for(let i = 0; i < len; i++) {
// result += splitWordsArr.pop() + ' ';
// }
//while문으로 한다면
let i = 0;
while( i < len) {
result += splitWordsArr.pop() + ' ';
i++;
}
// return result.trim();
// 역시 가장 짧은 건
return s.split(' ').filter(w => w !== '').reverse().join(' ')
};
- pop() 했을 때 길이가 즉각 줄어든다는 점에 주의할 것
- filter(w => w !== '') 해서 공백 없애는 방식에 익숙해질 것
'LeetCode' 카테고리의 다른 글
| 334. Increasing Triplet Subsequence (0) | 2026.01.17 |
|---|---|
| 238. Product of Array Except Self (0) | 2026.01.16 |
| 345. Reverse Vowels of a String (0) | 2026.01.14 |
| 605. Can place flowers (0) | 2026.01.13 |
Comments
