알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 06월 07일]
Leetcode - Remove All Adjacent Duplicates In String
문제: LeetCode - 1047. Remove All Adjacent Duplicates In String
코드
const removeDuplicates = (s) => {
const stack = [];
let nIdx = 0;
while (nIdx < s.length) {
if (stack[stack.length - 1] === s[nIdx]) stack.pop();
else stack.push(s[nIdx]);
nIdx++;
}
return stack.join('');
};
- 매개변수로 들어오는
s를 s.length만큼 순회하면서
현재 stack에 들어갈 문자 하나가 이미 stack에 들어있다면 pop 해주어야 함!
일반적인 경우엔 stack에 push!
Leetcode - Remove All Adjacent Duplicates In String II
문제: LeetCode - 1209. Remove All Adjacent Duplicates in String II
코드
const removeDuplicates = (s, k) => {
const stack = [];
const countStack = [];
let nIdx = 0;
while (nIdx < s.length) {
const stackLast = stack[stack.length - 1];
if (stackLast === s[nIdx]) {
if (k - 1 === countStack[countStack.length - 1]) {
for (let i = 0; i < k - 1; i++) stack.pop();
countStack.pop();
}
else {
stack.push(s[nIdx]);
countStack[countStack.length - 1]++;
}
} else {
stack.push(s[nIdx]);
countStack.push(1);
}
nIdx++;
}
return stack.join('');
};
- 들어오는 매개변수
k만큼 매개변수 s내에서 중복되는 문자를 제거하는 문제.
- 2개의 stack이 필요!
- 메인 stack
- 중복을 체크할 stack 필요
+ 메모
- 만약 챕터의 힌트가 없었다면 풀기 힘들었을 것!
Array나 String 문제를 정렬, 투 포인터, 바이너리 서치 말고도
stack 으로 해결할 생각도 해보기!
참고 자료
강의
알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 06월 07일]
Leetcode - Remove All Adjacent Duplicates In String
문제: LeetCode - 1047. Remove All Adjacent Duplicates In String
코드
s를s.length만큼 순회하면서현재
stack에 들어갈 문자 하나가 이미stack에 들어있다면 pop 해주어야 함!일반적인 경우엔
stack에 push!Leetcode - Remove All Adjacent Duplicates In String II
문제: LeetCode - 1209. Remove All Adjacent Duplicates in String II
코드
k만큼 매개변수s내에서 중복되는 문자를 제거하는 문제.+ 메모
Array나 String 문제를 정렬, 투 포인터, 바이너리 서치 말고도
stack 으로 해결할 생각도 해보기!
참고 자료
강의