본문 바로가기

문제 풀이8

Valid Parentheses Valid Parentheses 문자열의 유효성 검사하기 Solution class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if c in '([{': stack.append(c) elif not stack : return False else: o = stack.pop() if o == '[' and c == ']': continue if o == '(' and c ==')' : continue if o == '{' and c == '}' : continue return False return not stack 2022. 7. 10.
Odd Even Linked List Odd Even Linked List 입력 : 연결리스트, 길이는 0 ~ 10^4 출력 : 홀수 번째 Nodes를 앞으로(홀수 번째 Nodes 순서는 유지), 짝수 번째 Nodes는 뒤로 재배치(짝수 번째 Nodes 순서는 유지) 조건 : 공간복잡도 O(1) 시간복잡도 O(N) Solution 홀수번째 Node 끼리, 짝수번째 Node 끼리 모으고 마지막에 합치기 class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head evenhead = head.next odd, even = head, evenhead while even and e.. 2022. 6. 14.
Product of Array Product of Array Except Self Given : 정수 배열 nums[i] Return : 정수 배열 answer[i] 는 nums의 nums[i] 를 제외하고 곱한 값 나눗셈을 사용할수 없고 O(n) 으로 풀이 Solution 수를 왼쪽부터 곱셈한 결과와 오른쪽부터 곱셈한 결과를 기록 각 요소에 대해서 기록된 값을 바탕으로 자신을 제외하고 곱한값 계산 Code class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: size = len(nums) lefts=[1]*size rights=[1]*size for i in range(size-1): lefts[i+1] = lefts[i] * nums[i] rights.. 2022. 5. 11.
[leetcode] Group Anagrams Anagram A word or phrase formed by rearranging the letters of a different word or phrase Group Anagrams 문자열 array가 주어질때 anagram 끼리 그루핑 Solution 문자열을 구성하는 문자를 정렬한 결과가 같으면 같은 Group 으로 from collections import defaultdict class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: groups = defaultdict(list) for word in strs: groups[''.join(sorted(word))].append(word) return .. 2022. 4. 19.