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
- 건담헤드
- 건담
- 유루건
- 롱라이플
- 취미
- 발더스게이트
- LeetCode
- 제프딕슨
- 누룽지소금빵
- 맛집
- 포켓몬
- 메탈퍼즐
- 미앤아이
- 가챠
- 노노그램
- 블라인드박스
- 지리데칼
- 코테
- 게임
- 30mf
- 우리시대의역설
- 프라모델
- javascript
- 눈알빠지겠네
- 코딩테스트
- 발더스모드
- 바질토마토뭐시기
- 밥무하마드
- 지쿠악스
- DIY
Archives
- Today
- Total
.Zzumbong
[leetCode/JS] 1047. Remove All Adjacent Duplicates In String 본문
coding test/leetCode
[leetCode/JS] 1047. Remove All Adjacent Duplicates In String
쭘봉 2022. 11. 22. 21:01문제 설명
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
입출력 예
Example 1:
- Input: s = "abbaca"
- Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Example 2:
- Input: s = "azxxzy"
- Output: "ay"
Constraints
1 <= s.length <= 10^5
s consists of lowercase English letters.
내 솔루션
- 전체 반복 중 앞뒤로 중복된 글자를 만나면 삭제하고 i를 -1하여 검사한다.
- 메모리 사용량, 속도에서 아슬아슬하게 통과ㅋ slice 말고 array 변환 후 반복했으면 좀 나았을까
var removeDuplicates = function(s) {
let str = s;
for(let i = 0; i < str.length; i++) {
if(str[i] === str[i+1]){
str = str.slice(0,i) + str.slice(i+2);
i = i - 2 < 0 ? -1 : i - 2;
}
}
return str;
};
최고의 솔루션
- 현재와 이전 글자를 비교하여 삭제 해야 하기 때문에 Stack으로 접근한 듯.
- 이쁘고 깔끔, 속도와 메모리도 빠르고 가볍다.
var removeDuplicates = function(S) {
let res = [];
for(let i=0; i<S.length; i++){
if(S[i] !== res[res.length-1]) {
res.push(S[i]);
} else {
res.pop();
}
}
return res.join("");
};
감상평
- 가벼운 마음에 첫 leetcode를 풀고 통과해 뿌듯! 하지만 세상엔 똑똑이들이 많다는 것을 다시 한 번 실감.
'coding test > leetCode' 카테고리의 다른 글
[leetCode/JS] 2. Add Two Numbers (0) | 2022.11.23 |
---|---|
[leetCode/JS] 1. Two Sum (0) | 2022.11.22 |
[leetCode/JS] 151. Reverse Words in a String (0) | 2022.11.22 |
[leetCode/JS] 295. Find Median from Data Stream (0) | 2022.11.22 |
[leetCode/JS] 901. Online Stock Span (0) | 2022.11.22 |
Comments