본문 바로가기

Leetcode98

921. Minimum Add to Make Parentheses Valid 1. The time complexity is Θ(n²) in the worst case. class Solution(object): def minAddToMakeValid(self, S): """ :type S: str :rtype: int """ while "()" in S: S = S.replace("()", "") return len(S) 2. Easy to understand class Solution(object): def minAddToMakeValid(self, S): """ :type S: str :rtype: int """ stack = [] count = 0 for i in S: if i == '(': stack.append(i) elif stack: stack.pop() else: .. 2020. 7. 22.
20. Valid Parentheses class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ # The stack to keep track of opening brackets. stack = [] # Hash map for keeping track of mappings. This keeps the code very clean. # Also makes adding more types of parenthesis easier mapping = {")": "(", "}": "{", "]": "["} # For every bracket in the expression. for char in s: # If the character is an closing brack.. 2020. 7. 21.
844. Backspace String Compare 다른 사람 솔루션 class Solution: def backspaceCompare(self, S: str, T: str) -> bool: ans = '' ans_2 = '' for i in S: if i == '#': ans = ans[:-1] else: ans += i for i in T: if i == '#': ans_2 = ans_2[:-1] else: ans_2 += i return ans == ans_2 list가 아닌 string을 활용해서 stack 2020. 7. 21.
682. Baseball Game class Solution: def calPoints(self, ops: List[str]) -> int: a=[] for i in ops: if i=='C': a.pop() elif i=='D': a.append(a[-1]*2) elif i=='+': a.append(a[-1]+a[-2]) else: a.append(int(i)) return sum(a) int 조건을 처음으로 하기보다는 맨 마지막으로 넣어서 2020. 7. 19.
496. Next Greater Element I Wrong Answer class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: res = [] for i in range(len(nums1)): idx = nums2.index(nums1[i]) # error if last value in num2 == num1's some if nums2[-1] == nums2[idx]: # if match last value res.append(-1) elif nums2[idx] List[int]: # nums1 is a subset of nums2 result = [] for i, n in list(enumerate(nums1)): ind = nums2.. 2020. 7. 6.
1047. Remove All Adjacent Duplicates In String class Solution: def removeDuplicates(self, S: str) -> str: check = [] for s in S: if len(check)>0 and check[-1] == s: check.pop() else: check.append(s) return "".join(check) pop을 사용해야 겠다고는 생각했지만 if len(check)>0 and check[-1] == s 이 조건문을 만드는 것이 가장 어려운 부분이였다. 이번에도 혼자서 해결이 안되서 보고 풀었다.. 출력을 해보면 s check a a b a, b b a a [] c c a c, a 이게 머릿속에 빠르게 입력이 안되는게 답답 2020. 7. 5.
1441. Build an Array With Stack Operations class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: ls = list(range(1, n+1)) ans = [] for i in range(n): if ls[i] in target: ans.append("Push") else: ans.append("Push") ans.append("Pop") return ans 헤맷던 점은 target list와 매칭을 어떻게 시켜야할지 잘 안되서 discussion에 가서 다른 사람 풀이를 보니 list를 하다 더 만들어서 매칭시킴 여기서 한 가지 더 조건이 있었어야 되는데 test case가 [1,2] 4 일때 이미 target과 매칭이 끝났을때 stack을 멈추고 리턴하는걸 넣어.. 2020. 7. 1.
1021. Remove Outermost Parentheses STACK 말그대로 outermost parentheses를 제거하고 남은 string을 출력하는 문제 cnt 변수를 활용해서 list에 append하는 조건을 만들어서 해결 class Solution: def removeOuterParentheses(self, S: str) -> str: res = [] check = 0 for s in S: if s == "(" : check += 1 if check > 1 : # checking if it starts new paren or already added to "res" list res.append(s) if s == ")": check -= 1 if check >= 1: res.append(s) return "".join(res) 잘 안될때는 노트에 t.. 2020. 6. 30.