본문 바로가기

코테 준비/Stack5

[LeetCode] 1008. Construct Binary Search Tree from Preorder Traversal I. DescriptionII. Code# Definition for a binary tree node.class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # # __repr__ 메서드 추가 # def __repr__(self): # return f"TreeNode(val={self.val})" class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: .. 2025. 1. 26.
[LeetCode] 1006. Clumsy Factorial I. DescriptionII. Codeclass Solution: def clumsy(self, n: int) -> int: result = 0 add_or_sub = 1 for i in range(n, -1, -4): if i == 3: return (result + add_or_sub * 6) if i == 2: return (result + add_or_sub * 2) if i == 1: return (result + add_or_sub * 1) if i == 0: ret.. 2025. 1. 26.
[LeetCode] 1003. Check If Word Is Valid After Substitutions I. DescriptionII. Codeclass Solution: def isValid(self, s: str) -> bool: if 'abc' in s: return self.isValid(s.replace('abc', '')) if s == '': return True return False같은 방식을 계속 반복해야 하므로 재귀함수를 사용했다. 2025. 1. 26.
[LeetCode] 1441. Build an Array with Stack Operations I. DescriptionII. Codeclass Solution: def buildArray(self, target: List[int], n: int) -> List[str]: # 초기화 output_list = [] checked = 1 for i in range(1, n+1): if i in target: while checked != i: output_list.append("Push") output_list.append("Pop") checked += 1 .. 2025. 1. 26.
[LeetCode] 2487. Remove Nodes From Linked List I. Description문제 링크: https://leetcode.com/problems/remove-nodes-from-linked-list/description/?envType=problem-list-v2&envId=stackII. Codei)# # Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution: def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: stack = [] .. 2025. 1. 24.