본문 바로가기

항해99 chap02

(26)
스택 수열 - 스택 스택수열 백준 스택 수열. stack =[] answer =[] n = int(input()) # 8 (입력 개수) arr = [int(input()) for _ in range(n)] # [4, 3, 6, 8, 7, 5, 2, 1] (입력 배열) index = 0 for i in range(1,n+1): # 1 2 3 4 5 6 7 8 stack.append(i) # 스택이 비어있으면 안되서 answer.append('+') while stack and stack[-1] == arr[index]: # 스택이 안비어있고 스택의 마지막이 배열의 인덱스와 같으면 stack.pop() answer.append('-') index+=1 #인덱스 올려주기 if stack: print(..
괄호 - 스택 괄호 백준 괄호. 아이디어 여는 괄호 ( 닫는 괄호 )가 순서와 짝이 맞아야한다. 닫는 괄호보다 여는 괄호가 먼저 나와야한다. 여는 괄호를 스택에 푸시하고 닫는 괄호가 나오면 팝하여 지워나가서 입력받은 괄호 문자열을 모두 검사하였을 경우 스택이 비어있으면 YES를 출력한다. 정답코드 num = int(input()) for i in range(num): stack = [] s = input() check = True for char in s: if char == "(": stack.append(char) else: if not stack: print("NO") check = False break stack.pop() if check == True: # 체크 변수를 넣어준 이유 : 위에 포문에서 닫이는 괄..
중복 문자 제거 - 스택 중복 문자 제거 스택 중복된 문자를 제거하고 사전식 순서로 나열하라 입력 : "bcabc" 출력 : "abc" 입력 : "cbacdcbc" 출력 : "acdb" from collections import Counter def solution(s): counter,seen,stack = Counter(s),set(),[] for char in s: counter[char]-=1 if char in seen: continue #뒤에 붙일 문자가 남아있다면 스택에서제거 while stack and char0: seen.remove(stack.pop()) stack.append(char) seen.add(char) return ''.join(stack) print(solution("cbacdcbc")) 풀이 만..
일일온도 - 스택 일일 온도 스택 매일의 화씨 온도 리스트를 받아 , 더 따듯한 날을 위해서는 며칠을 기다려야하는 지를 출력. T = [73, 74, 75, 71, 69, 72, 76, 73] def dailyTemperatures(T): stack=[] answer = [0]* len(T) for i ,j in enumerate(T): while stack and j>T[stack[-1]]: last = stack.pop() answer[last] =i-last stack.append(i) return answer print(dailyTemperatures(T)) 아이디어 현재의 인덱스를 계속 스택에 쌓아 두다가, 이전보다 상승하는 지점에서 현재 온도와 스택에 쌓아둔 인덱스 의 지점의 온도를 비교하여 인덱스의 차이를 정..
홀짝 연결 리스트 홀짝 연결 리스트 연결 리스트를 홀수 노드 다음에 짝수 노드가 오도록 재 구성 하라. 제약조건 공간복잡도 O(1) 시간 복잡도 O(n) class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def print_all(self): while self: print(self.val, end=' ') self=self.next print() def oddEvenList( head: Optional[ListNode]) -> Optional[ListNode]: if head is None: #예외처리 return None odd = head even = head.next even_head = head.n..
역순 연결 리스트 #역순 연결 리스트 연결리스트를 뒤집어라 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def print_all(self): while self: print(self.val, end=' ') self= self.next print() def reverseList(head): #반복 node, prev = head, None while node: next, node.next = node.next, prev # 현재 노드에서 가르키는 노드를 next에, 현재 노드가 가르키고 있던것을 prev로 prev, node = node, next # prev를 현재 노드로 최신화, node도 현재 ..
두 정렬 리스트의 병합 두 정렬 리스트의 병합 정렬되어 있는 두 연결 리스트를 합쳐라 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def print_all(self): while self: print(self.val, end=' ') self = self.next print() from typing import Optional class Solution: def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: if (not l1) or (l2 and l1.val > l2.val): # l1이 ..
배열 파티션 배열 파티션 n 개의 페어를 이용한 min(a,b)의 합으로 만들수 있는 가장 큰수를 출력해라 def arrayPairSum(nums): nums.sort() answer = 0 for i in range(len(nums)): if (i % 2 == 0): answer += nums[i] return answer nums = [1, 4, 3, 2] print(arrayPairSum(nums)) #아이디어 정렬되지 않은 배열을 오름차순으로 정렬을한다. ex) [1,2,3,4] min(a,b)의 합들중 가장 큰 수를 구하기 위해서는 짝수번째 수들의 합이다. 답지풀이 def arrayPairSum(nums): nums.sort() answer = 0 return sum(sorted(nums)[::2]) num..