Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions valid-parentheses/hi-rachel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// TC: O(N^2), SC: O(N)
// function isValid(s: string): boolean {
// let prevLength = -1;

// while (s.length !== prevLength) {
// prevLength = s.length;
// s = s.replace("()", "").replace("[]", "").replace("{}", "");
// }

// return s.length === 0;
// }

/**
* STACK 풀이
* TC: O(N), SC: O(N)
* 스택 방식 작동 순서
* for (const char of s) {
if (여는 괄호) {
스택에 push
} else {
스택에서 pop한 값이 char의 짝이 아니면 return false
}
}
*/
function isValid(s: string): boolean {
const stack: string[] = [];
const parentheseMap: Record<string, string> = {
")": "(",
"]": "[",
"}": "{",
};

for (const char of s) {
if (["(", "[", "{"].includes(char)) {
stack.push(char);
} else {
if (stack.pop() !== parentheseMap[char]) return false;
}
}
return stack.length === 0;
}

/**
* Python과 JS에서의 pop() 메서드 차이
* JS 같은 로직을 Python으로 바꾸면 Python에서만 다음과 같은 테스트 케이스 오류가 발생
* TEST CASE: "]", "){", ")(){}"
*
* [원인]
* if (stack.pop() !== parentheseMap[char]) return false; 비교시
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파이썬 풀이도 함께 적어주셔서 TS를 사용해본 적 없음에도 알고리즘을 잘 이해할 수 있었습니다.👍

* JavaScript에서는 빈 스택 pop() -> undefined 반환으로 비교 가능!
* Python에서는 빈 스택 pop() -> IndexError -> 오류 발생
*
* [해결책] - 예외 처리 필요
* pop 전에 not stack 체크 꼭 해주기
* not stack -> 스택이 비어 있다면 잘못된 닫는 괄호 먼저 나온 경우
*/

// PY 풀이
// class Solution:
// def isValid(self, s: str) -> bool:
// parentheseMap = {")" : "(", "]": "[", "}": "{"}
// stack = []
// open_parenthese = "([{"

// for char in s:
// if char in open_parenthese:
// stack.append(char)
// else:
// if (not stack or stack.pop() != parentheseMap[char]):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파이썬에서는 스택에 pop하기 전 반드시 비어있는지 확인해주어야 한다는 걸 저도 이번 문제 풀면서 새롭게 알게 되었습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@river20s 두 가지 언어의 차이를 느낄 수 있었던 풀이였습니다.

// return False

// return len(stack) == 0
Loading