Skip to content

[KwonNayeon] Week 6 solutions #1434

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
17 changes: 15 additions & 2 deletions valid-palindrome/KwonNayeon.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,35 @@

<Solution 1>
Time Complexity: O(n)
- 문자열 길이(n)에 비례함
- 정규식 처리, 소문자 변환, 역순 비교 모두 O(n)

Space Complexity: O(n)
- 변환된 문자열과 역순 문자열을 저장하는 공간이 필요함

풀이 방법:
- 문자열에서 알파벳과 숫자만 남기고 모두 소문자로 변환
- 변환된 문자열과 그 역순이 같은지 비교
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
s = re.sub(r'[^a-zA-z0-9]', '', s).lower()
s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
if s == s[::-1]:
return True
return False
"""
<Solution 2>
Time Complexity: O(n)
- 팰린드롬일 경우, 각 문자를 한 번씩 검사
- 팰린드롬일 경우, 각 문자를 한 번씩 검사함

Space Complexity: O(1)
- left, right 포인터 외에 추가 공간 사용 없음

풀이 방법:
- 양쪽 끝에서 시작하는 두 포인터(left, right)를 활용한 방법
- 알파벳/숫자가 아닌 문자는 건너뛰며 포인터 이동
- 두 포인터가 가리키는 문자가 다르면 즉시 False 반환
- 모든 비교가 일치하면 True 반환
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
Expand Down
40 changes: 21 additions & 19 deletions valid-parentheses/KwonNayeon.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,30 @@
- 따라서 입력 크기에 비례하는 O(n) 공간 필요

풀이방법:
1. 스택을 사용하여 여는 괄호('(', '{', '[')를 저장
2. Dictionary를 사용해 닫는 괄호와 여는 괄호의 쌍을 O(1)로 매칭
3. 문자열을 순회하면서:
- 여는 괄호는 스택에 추가
- 닫는 괄호가 나오면:
a) 스택이 비어있거나
b) 스택 최상단의 괄호가 현재 닫는 괄호와 매칭되지 않으면
-> 잘못된 괄호 문자열
- 매칭되는 경우 스택에서 pop
4. 모든 순회가 끝난 후 스택이 비어있어야 올바른 괄호 문자열
- key: 닫는 괄호, value: 대응하는 여는 괄호
- 현재 문자가 닫는 괄호인 경우
- 스택이 비어있다면(짝이 없음) -> False
- 스택에서 가장 최근에 추가된 여는 괄호를 꺼냄, 만약 대응하는 값이 아니라면 -> False
- 현재 문자가 여는 괄호인 경우 -> stack에 추가
- 모든 문자 처리 후, 스택이 비어있으면 모든 괄호의 짝이 맞음 (True)
"""
class Solution:
def isValid(self, s: str) -> bool:
stack = []
pairs = {')': '(', '}': '{', ']': '['}


mapping = {')': '(', '}': '{', ']': '['}

for char in s:
if char in '({[':
stack.append(char)
else:
if not stack or stack[-1] != pairs[char]:
if char in mapping:
if not stack:
return False
stack.pop()

return len(stack) == 0

top = stack.pop()

if mapping[char] != top:
return False

else:
stack.append(char)

return not stack
Copy link
Contributor

Choose a reason for hiding this comment

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

코드가 업데이트 되면서 더욱 깔끔하게 정리된 것 같습니다. 👍