본문 바로가기

반응형

Algorithm/LeetCode

(14)
[LeetCode][Python3] 98. Validate Binary Search Tree # 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 class Solution: def isValidBST(self, root: TreeNode) -> bool: def isValid(node:TreeNode,low=-math.inf,high=math.inf): if not node: return True else: if(node.val=high): return False return isValid(node.left,low,node.val) and isValid(no..
[LeetCode][Python3] 17. Letter Combinations of a Phone Number 풀이 1 class Solution: def letterCombinations(self, digits: str) -> List[str]: if digits=="": return [] result=[] letter={'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6':['m','n','o'],'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']} def dfs(prefix: str,digits:str,length:int): if(length == len(digits)): result.append(prefix) return else: for i in letter[dig..
[LeetCode][Python3] 21. Merge Two Sorted Lists 풀이 1 class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: ary=[] while l1 or l2: if l1: ary.append(l1.val) l1=l1.next elif l2: ary.append(l2.val) l2=l2.next ary.sort() if len(ary)>0: l3=ListNode(ary[0],None) itr = l3 for i in ary[1:]: node = ListNode(i,None) itr.next=node itr=itr.next return l3 return None ary.sort() 을 통해 정렬을 할 수 있지만 이는 알고리즘 공부에 도움이 되지 않는다고 생각했다. 풀이 2..
[LeetCode][Python3] 20. Valid Parentheses class Solution: def isValid(self, s: str) -> bool: stack=[] if(len(s)%2==1): return False for c in s: if(c=="(" or c=="[" or c=="{"): stack.append(c) else: if len(stack)==0: return False popItem = stack.pop() if(popItem == '('): if(c==')'): continue else: return False elif(popItem == '['): if(c==']'): continue else: return False elif(popItem == '{'): if(c=='}'): continue else: return False if le..
[LeetCode][Python3] 14. Longest Common Prefix 14. Longest Common Prefix 1. 수평 탐색 class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if(len(strs)==0): return "" prefix = strs[0] for i in range(1,len(strs)): while(strs[i].find(prefix)!=0): prefix = prefix[0:len(prefix)-1] if(len(prefix)==0): return "" return prefix 풀이 접두사 prefix 를 strs[0]으로 설정한 후, strs의 각 요소에게 접근하면서 prefix를 수정한다. 접두사는 단어의 [0:?]에 존재한다는 특징이 있으므로 prefix=strs[..
[LeetCode][Python3] 1.two-sum github.com/dbwp031/LeetCode dbwp031/LeetCode my solution codes of problems from leetcode. Contribute to dbwp031/LeetCode development by creating an account on GitHub. github.com 전체 코드입니다. class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: length = len(nums) for i in range(0,length): for j in range(i+1,length): if(nums[i]+nums[j] == target): return [i,j]

반응형