├── .gitignore ├── README.md ├── 곽태웅 ├── 2.4 ├── Circular_Deque ├── Coures_Schedule ├── KAKAO_String ├── Keys_and_Rooms ├── Longest Substring ├── Max_Sum_of_Rect ├── String_Anagrams ├── String_Log_Files ├── Top K Frequent Element ├── hanoi ├── leetcode_1 ├── leetcode_2 ├── 쇠막대기 │ └── solution.py └── 주식문제 │ └── solution.py ├── 김인호 ├── (그래프)Course Schedule │ └── solution.py ├── (그래프)Is Graph Bipartite │ └── solution.py ├── (그래프)Keys and Rooms │ └── solution.py ├── (링크드리스트)Remove Duplicates │ └── solution.py ├── (링크드리스트)RotateList │ └── solution.py ├── (링크드리스트)책_2-4.py │ └── solution.py ├── (문자열)Group Anagrams │ └── solution.py ├── (문자열)Reorder Data in Log Files │ └── solution.py ├── (문자열)문자열 압축 │ └── solution.py ├── (스택,큐)쇠막대기 │ └── solution.py ├── (스택,큐)주식가격 │ └── solution.py ├── (스택,큐)책_3-4.py │ └── solution.py ├── (재귀)K-th Symbol in Grammar │ └── K-th Symbol in Grammar.py ├── (큐)Design Circular Queue │ └── solution.py ├── (큐)Max Sum of Rectangle No Larger Than K │ └── solution.py ├── (해시)Longest Substring Without Repeating Characters │ └── solution.py └── (해시)Top K Frequent Elements │ └── solution.py ├── 백승연 ├── Hash-longest substring │ └── solution.py ├── Hash-top k frequent elements │ ├── solution.py │ └── solution2.py ├── Queue-Design Circular Queue │ └── solution.py ├── Queue-Printer │ └── solution.py ├── Stack- Hanoi │ └── solution.py ├── 쇠막대기 │ └── solution.py └── 주식가격 │ └── solution.py ├── 송민수 ├── 622. Design Circular Queue ├── hanoi ├── leetcode 779.py ├── 프로그래머스-쇠막대기.py └── 프로그래머스-주식가격.py ├── 안형욱 ├── design-circular-queue │ └── solution.py ├── hanoi-top │ └── solution.py ├── remove-duplicates-from-sorted-list-ii │ └── solution.py ├── rotate-list │ └── solution.py ├── 쇠막대기 │ └── solution.py └── 주식가격 │ └── solution.py ├── 이하은 ├── 1_Stack │ ├── 쇠막대기.py │ └── 주식문제.py └── 2_linked_list │ ├── 2.4_sorted_linked_list.py │ ├── remove_duplicates_from_list.py │ └── rotate_list.py ├── 정승호 ├── 2016 │ └── solution.py ├── 0만들기 │ └── solution.py ├── 124_나라의_숫자 │ └── solution.py ├── 3Sum │ └── solution.py ├── 3진법_뒤집기 │ └── solution.py ├── AC │ └── solution.py ├── DFS와BFS │ └── solution.py ├── LRU_Cache │ └── solution.py ├── N으로_표현 │ └── solution.py ├── Remove-Duplicates-from-Sorted-List-II │ └── solution.py ├── SQL │ ├── Revising_the_Select_Query_II │ │ └── solution.sql │ ├── japanese-cities-attributesselect-by-id │ │ └── solution.sql │ ├── japanese-cities-name │ │ └── solution.sql │ ├── more-than-75-marks │ │ └── solution.sql │ ├── name-of-employees │ │ └── solution.sql │ ├── salary-of-employees │ │ └── solution.sql │ ├── select-all │ │ └── solution.sql │ ├── select-by-id │ │ └── solution.sql │ ├── the-pads │ │ └── solution.sql │ ├── weather-observation-station-1 │ │ └── solution.sql │ ├── weather-observation-station-10 │ │ └── solution.sql │ ├── weather-observation-station-11 │ │ └── solution.sql │ ├── weather-observation-station-12 │ │ └── solution.sql │ ├── weather-observation-station-3 │ │ └── solution.sql │ ├── weather-observation-station-4 │ │ └── solution.sql │ ├── weather-observation-station-5 │ │ └── solution.sql │ ├── weather-observation-station-6 │ │ └── solution.sql │ ├── weather-observation-station-7 │ │ └── solution.sql │ ├── weather-observation-station-8 │ │ └── solution.sql │ ├── weather-observation-station-9 │ │ └── solution.sql │ └── what-type-of-triangle │ │ └── solution.sql ├── Sherlock_and_the_Valid_String │ └── solution.py ├── Swap-Node-in-Pairs │ └── solution.py ├── Two-Sum │ └── solution.py ├── Z │ └── solution.py ├── alphabet-board-path │ └── solution.py ├── balanced-binary-tree │ └── solution.py ├── best-time-to-buy-and-sell-stock-ii │ └── solution.py ├── best-time-to-buy-and-sell-stock │ └── solution.py ├── binary-search-tree-to-greater-sum-tree │ └── solution.py ├── binary-search │ └── solution.py ├── cheapest-flights-within-k-stops │ └── solution.py ├── combination-sum │ └── solution.py ├── combinations │ └── solution.py ├── contains-duplicate │ └── solution.py ├── convert-sorted-array-to-binary-search-tree │ └── solution.py ├── daily-temperatures │ └── solution.py ├── design-circular-queue │ └── solution.py ├── design-hashmap │ └── solution.py ├── diameter-of-binary-tree │ └── solution.py ├── different-ways-to-add-parentheses │ └── solution.py ├── find-n-unique-integers-sum-up-to-zero │ └── solution.py ├── first-bad-version │ └── solution.py ├── flood-fill │ └── solution.py ├── gas-station │ └── solution.py ├── group-anagrams │ └── solution.py ├── implement-queue-using-stacks │ └── solution.py ├── implement-stack-using-queues │ └── solution.py ├── invert-binary-tree │ └── solution.py ├── is-graph-bipartite │ └── solution.py ├── jump-game-iii │ └── solution.py ├── jump-game │ └── solution.py ├── k-th-symbol-in-grammar │ └── solution.py ├── keys-and-rooms │ └── solution.py ├── letter-combinations-of-a-phone-number │ └── solution.py ├── longest-palindromic-substring │ └── solution.py ├── longest-substring-without-repeating-characters │ └── solution.py ├── longest-univalue-path │ └── solution.py ├── max-area-of-island │ └── solution.py ├── maximum-depth-of-binary-tree │ └── solution.py ├── merge-two-binary-trees │ └── solution.py ├── middle-of-the-linked-list │ └── solution.py ├── minimum-deletions-to-make-character-frequencies-unique │ └── solution.py ├── minimum-distance-between-bst-nodes │ └── solution.py ├── minimum-height-trees │ └── solution.py ├── move-zeroes │ └── solution.py ├── network-delay-time │ └── solution.py ├── number-of-islands │ └── solution.py ├── partition-labels │ └── solution.py ├── permutation-in-string │ └── solution.py ├── permutations │ └── solutions.py ├── product-of-array-except-self │ └── solution.py ├── queue-reconstruction-by-height │ └── solution.py ├── range-sum-of-bst │ └── solution.py ├── reconstruct-itinerary │ └── solution.py ├── regular-expression-matching │ └── solution.py ├── remove-nth-node-from-end-of-list │ └── solution.py ├── reorder-data-in-log-files │ └── solution.py ├── reverse-string │ └── solution.py ├── reverse-words-in-a-string-iii │ └── solution.py ├── rotate-list │ └── solution.py ├── search-a-2d-matrix │ └── solution.py ├── search-insert-position │ └── solution.py ├── serialize-and-deserialize-binary-tree │ └── solution.py ├── solution.py ├── squares-of-a-sorted-array] │ └── solution.py ├── subsets │ └── solution.py ├── top-k-frequent-elements │ └── solution.py ├── trapping-rain-water │ └── solution.py ├── valid-palindrome │ └── solution.py ├── word-search │ └── solution.py ├── x만큼_간격이_있는_n개의_숫자 │ └── solution.py ├── 가운데_글자_가져오기 │ └── solution.py ├── 같은_숫자는_싫어 │ └── solution.py ├── 괄호 │ └── solution.py ├── 괄호_변환 │ └── solution.py ├── 괄호_제거 │ └── solution.py ├── 괄호의_값 │ └── solution.py ├── 구명보트 │ └── solution.py ├── 균형잡힌_세상 │ └── solution.py ├── 기능개발 │ └── solution.py ├── 기술면접 │ └── 자바 │ │ └── README.md ├── 나누어_떨어지는_숫자_배열 │ └── solution.py ├── 나는야_포켓몬_마스터_이다솜 │ └── solution.py ├── 내적 │ └── solution.py ├── 다리를_지나는_트럭 │ └── solution.py ├── 다트게임 │ └── solution.py ├── 단지번호붙이기 │ └── solution.py ├── 더_맵게 │ └── solution.py ├── 덱 │ └── solution.py ├── 두_개_뽑아서_더하기 │ └── solution.py ├── 두_정수_사이의_합 │ └── solution.py ├── 뒤집기 │ └── solution.py ├── 로봇_청소기 │ └── solution.py ├── 맥주마시면서걸어가기 │ └── solution.py ├── 멀쩡한_사각형 │ └── solution.py ├── 문자열_내_p와_y의_개수 │ └── solution.py ├── 문자열_내림차순으로_배치하기 │ └── solution.py ├── 문자열_내맘대로_정렬하기 │ └── solution.py ├── 문자열_다루기_기본 │ └── solution.py ├── 문자열_집합 │ └── solution.py ├── 문자열을_정수로_바꾸기 │ └── solution.py ├── 미로탐색 │ └── solution.py ├── 바이러스 │ └── solution.py ├── 비밀지도 │ └── solution.py ├── 상호_평가 │ └── solution.py ├── 서울에서_김서방_찾기 │ └── solution.py ├── 세용액 │ └── solution.py ├── 소수_찾기 │ └── solution.py ├── 소수찾기 │ └── solution.py ├── 쇠막대기 │ └── solution.py ├── 수_찾기 │ └── solution.py ├── 수박수박수박수박수박수 │ └── solution.py ├── 수식_최대화 │ └── solution.py ├── 숨바꼭질 │ └── solution.py ├── 스킬트리 │ └── solution.py ├── 스타트링크 │ └── solution.py ├── 스택 │ └── solution.py ├── 스택_수열 │ └── solution.py ├── 시공의폭풍속으로 │ └── solution.py ├── 실패율 │ └── solution.py ├── 아기_상어 │ └── solution.py ├── 안전영역 │ └── solution.py ├── 약수의_합 │ └── solution.py ├── 예산 │ └── solution.py ├── 완주하지_못한_선수 │ └── solution.py ├── 요세푸스_문제 │ └── solution.py ├── 위장 │ └── solution.py ├── 이상한_문자_만들기 │ └── solution.py ├── 자릿수_더하기 │ └── solution.py ├── 자연수_뒤집어_배열로_만들기 │ └── solution.py ├── 전화번호_목록 │ └── solution.py ├── 정수_내림차순으로_배치하기 │ └── solution.py ├── 정수_제곱근_판별 │ └── solution.py ├── 제일_작은수_제거하기 │ └── solution.py ├── 조이스틱 │ └── solution.py ├── 좋은_단어 │ └── solution.py ├── 주식가격 │ └── soluton.py ├── 직업군_추천하기 │ └── solution.py ├── 짝수와_홀수 │ └── solution.py ├── 촌수계산 │ └── solution.py ├── 최대_힙 │ └── solution.py ├── 최대공약수와_최소공배수 │ └── solution.py ├── 치킨_배달 │ └── solution.py ├── 카드2 │ └── solution.py ├── 카드_놓기_18115 │ └── solution.py ├── 카펫 │ └── solution.py ├── 콜라츠_추측 │ └── solution.py ├── 쿼드압축_후_숫자세기 │ └── solution.py ├── 큐 │ └── solution.py ├── 큐_2 │ └── solution.py ├── 크레인_인형뽑기 │ └── solution.py ├── 큰수만들기 │ └── solution.py ├── 키로거 │ └── solution.py ├── 키패드_누르기 │ └── solution.py ├── 타겟_넘버 │ └── solution.py ├── 탑 │ └── solution.py ├── 토마토 │ └── solution.py ├── 파이프_옮기기_1 │ └── solution.py ├── 평균_구하기 │ └── solution.py ├── 평범한배낭 │ └── solution.py ├── 풍선_터뜨리기 │ └── solution.py ├── 풍선_터뜨리기_BOJ │ └── solution.py ├── 프린터_큐 │ └── solution.py ├── 하노이탑 │ └── solution.py ├── 하샤드_수 │ └── solution.py ├── 핸드폰_번호_가리기 │ └── solution.py ├── 행렬의_덧셈 │ └── solution.py ├── 회전하는_큐 │ └── solution.py ├── 후보_추천하기 │ └── solution.py ├── 후위_표기식 │ └── solution.py └── 후위_표기식2 │ └── solution.py └── 한석희 ├── RemoveDuplicatesfromSortedList └── solution1.swift ├── RotateList └── solution-3.swift ├── xDivide └── solution.swift ├── 큐_하노이탑 └── solution.swift ├── 쇠막대기 └── solution.py ├── 주식가격 ├── solution_1차_시도.py ├── solution_2차_시도.py └── solution_3차_시도.py ├── 큐_DesignCircularDeque └── solution.swift ├── 큐_MaxSumOfRect └── solution.swift └── 큐_하노이탑 └── solution.swift /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /venv 3 | /안형욱/.idea 4 | /안형욱/venv 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 파이썬 코딩 테스트 스터디 2 | > 모두 힘내서 네이버도 뿌수자! 3 | 4 | 5 | ## Pull request 규칙 6 | 7 | 1. 먼저 python-coding-study 저장소를 포크해 주세요 8 | 2. 포크한 저장소를 클론해 줍니다. 9 | 3. `PR-{본인 이니셜}-{회차}-{날짜}`의 형태로 브랜치를 만들어 주세요. Ex) `PR-JSH-01-0728` 10 | 4. 본인 이름의 디렉토리를 만들어서 그 아래에 문제와 코드를 작성해줍니다. Ex) `python-coding-study/정승호/쇠막대기/solution.py` 11 | 5. Pull request를 해주시고, 승인이 나면 merge 해주시면 됩니다. 12 | 13 | 14 | 커밋 메세지는 목적에 맞게 작성해주시면 됩니다. Ex) `쇠막대기` , `쇠막대기 기능 개선`.... 15 | 16 | ## 1회차(2020.08.04) - Stack 17 | 18 | > 담당자 : 정승호 19 | > 20 | -------------------------------------------------------------------------------- /곽태웅/2.4: -------------------------------------------------------------------------------- 1 | 채점할 수가 없어서 우선 생각한 알고리즘만 업로드. 2 | 3 | 1. 두개의 링크드리스트를 만든다.(1번 작은 링크드리스트 넣는 공간, 2번 크거나 같은 링크드리스트 넣는 공간) 4 | 2. x랑 값을 비교해서 작으면 1번 링크드리스트에 넣는다 5 | 3. x랑 값을 비교해서 크거나 같으면 2번 링크드리스트에 넣는다 6 | 4. 1번 링크드리스트 끝과 2번 링크드 리스트 헤더랑 연결한다 7 | 5. 합친 링크드 리스트를 반환한다. 8 | -------------------------------------------------------------------------------- /곽태웅/Circular_Deque: -------------------------------------------------------------------------------- 1 | class MyCircularQueue: 2 | 3 | def __init__(self, k: int): 4 | """ 5 | Initialize your data structure here. Set the size of the queue to be k. 6 | """ 7 | self.k = k 8 | self.que = [] 9 | 10 | def enQueue(self, value: int) -> bool: 11 | """ 12 | Insert an element into the circular queue. Return true if the operation is successful. 13 | """ 14 | if len(self.que) == self.k: return False 15 | else: 16 | self.que.append(value) 17 | return True 18 | 19 | def deQueue(self) -> bool: 20 | """ 21 | Delete an element from the circular queue. Return true if the operation is successful. 22 | """ 23 | if len(self.que) == 0: return False 24 | else: 25 | del self.que[0] 26 | return True 27 | 28 | def Front(self) -> int: 29 | """ 30 | Get the front item from the queue. 31 | """ 32 | if len(self.que) == 0: return -1 33 | else: return self.que[0] 34 | 35 | def Rear(self) -> int: 36 | """ 37 | Get the last item from the queue. 38 | """ 39 | if len(self.que) == 0: return -1 40 | else: return self.que[-1] 41 | 42 | 43 | def isEmpty(self) -> bool: 44 | """ 45 | Checks whether the circular queue is empty or not. 46 | """ 47 | if len(self.que) == 0: return True 48 | else: return False 49 | 50 | def isFull(self) -> bool: 51 | """ 52 | Checks whether the circular queue is full or not. 53 | """ 54 | if len(self.que) == self.k: return True 55 | else: return False 56 | 57 | 58 | 59 | # Your MyCircularQueue object will be instantiated and called as such: 60 | # obj = MyCircularQueue(k) 61 | # param_1 = obj.enQueue(value) 62 | # param_2 = obj.deQueue() 63 | # param_3 = obj.Front() 64 | # param_4 = obj.Rear() 65 | # param_5 = obj.isEmpty() 66 | # param_6 = obj.isFull() 67 | -------------------------------------------------------------------------------- /곽태웅/Coures_Schedule: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 3 | temp = {} 4 | for i in range(len(prerequisites)): 5 | temp[prerequisites[i][0]] = temp.get(prerequisites[i][0], []) + [prerequisites[i][1]] 6 | N = list(temp.keys()) 7 | if prerequisites[i][1] in N: 8 | if prerequisites[i][0] in temp[prerequisites[i][1]]: 9 | return False 10 | for j in temp: 11 | if prerequisites[i][1] in N: 12 | if prerequisites[i][1] in temp[j]: 13 | temp[prerequisites[i][0]] = temp.get(prerequisites[i][0], []) + temp[prerequisites[i][1]] 14 | for j in temp: 15 | if prerequisites[i][0] in temp[j]: 16 | temp[j] = temp.get(j, []) + temp[prerequisites[i][0]] 17 | 18 | return True 19 | -------------------------------------------------------------------------------- /곽태웅/KAKAO_String: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer = 10000 3 | for i in range(1,int(len(s)/2) + 1): 4 | pre_cnt = i 5 | temp_word = '' 6 | check = 0 7 | j = 0 8 | min_val = 0 9 | while i*j < len(s): 10 | j += 1 11 | if j == 1: 12 | temp_word = s[0:pre_cnt] 13 | else: 14 | if temp_word == s[pre_cnt:i*j]: 15 | check += 1 16 | else: 17 | temp_word = s[pre_cnt:i*j] 18 | check -= 1 19 | if check == -1: 20 | min_val += i 21 | check = 0 22 | else: 23 | min_val += 1 + i 24 | check = 0 25 | pre_cnt = i*j 26 | if check == 0: 27 | min_val += i - (i*j - len(s)) 28 | check = 0 29 | else: 30 | min_val += 1 + i 31 | check = 0 32 | if min_val < answer: 33 | answer = min_val 34 | 35 | return answer 36 | -------------------------------------------------------------------------------- /곽태웅/Keys_and_Rooms: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 3 | open_door = [0 for i in range(len(rooms))] 4 | open_door[0] = 1 5 | def went(key): 6 | for i in key: 7 | if open_door[i] == 1: 8 | continue 9 | open_door[i] = 1 10 | for j in rooms[i]: 11 | if open_door[j] != 1: 12 | went(rooms[i]) 13 | 14 | went(rooms[0]) 15 | if 0 in open_door: 16 | return False 17 | return True 18 | -------------------------------------------------------------------------------- /곽태웅/Longest Substring: -------------------------------------------------------------------------------- 1 | 1차 실패- 타임아웃 2 | ============================================================== 3 | class Solution: 4 | def lengthOfLongestSubstring(self, s: str) -> int: 5 | temp = "" 6 | temp_s = s 7 | max = 0 8 | while len(temp_s) > max: 9 | for i in temp_s: 10 | if i in temp: 11 | if max < len(temp): 12 | max = len(temp) 13 | temp = i 14 | else: 15 | temp = temp + i 16 | if max < len(temp): 17 | max = len(temp) 18 | temp_s = temp_s[1:] 19 | temp = "" 20 | return max 21 | ============================================================== 22 | -------------------------------------------------------------------------------- /곽태웅/Max_Sum_of_Rect: -------------------------------------------------------------------------------- 1 | ###실패.. 2 | 3 | 4 | import numpy 5 | class Solution: 6 | def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: 7 | while True: 8 | #행 다 더한 값 9 | row = [] 10 | for i in matrix: row.append(sum(i)) 11 | #열 다 더한 값 12 | col = [] 13 | for i in range(len(matrix[0])): 14 | temp_col = 0 15 | for j in range(len(matrix)): temp_col += matrix[j][i] 16 | col.append(temp_col) 17 | 18 | temp_max = sum(col) 19 | if temp_max > k: 20 | temp_max = None 21 | for i in row: 22 | if i > k: None 23 | elif temp_max == None: temp_max = i 24 | elif temp_max < i: temp_max = i 25 | for i in col: 26 | if i > k: None 27 | elif temp_max == None: temp_max = i 28 | elif temp_max < i: temp_max = i 29 | 30 | temp_i = None 31 | temp_j = None 32 | where = None 33 | #열 더한 값 최대값 축출 34 | for i in range(len(col)): 35 | temp_col = 0 36 | for j in range(i, len(col)): 37 | temp_col += col[j] 38 | if temp_col > k: None 39 | elif temp_col > temp_max: 40 | temp_max = temp_col 41 | temp_i = i 42 | temp_j = j 43 | where = 1 44 | 45 | #행 더한 값 최대값 축출 46 | for i in range(len(row)): 47 | temp_row = 0 48 | for j in range(i, len(row)): 49 | temp_row += row[j] 50 | if temp_row > k: None 51 | elif temp_row > temp_max: 52 | temp_max = temp_row 53 | temp_i = i 54 | temp_j = j 55 | where = 2 56 | 57 | ## 최대값 갱신 시 매트릭스 갱신 58 | if temp_i != None: 59 | if where == 1: 60 | max_matrix = numpy.zeros((len(row), temp_j-temp_i+1), int) 61 | for i in range(len(row)): 62 | cnt = 0 63 | for j in range(temp_i, temp_j + 1): 64 | max_matrix[i][cnt] = matrix[i][j] 65 | cnt += 1 66 | if where == 2: 67 | max_matrix = numpy.zeros((temp_j-temp_i+1, len(col)), int) 68 | cnt = 0 69 | for i in range(temp_i, temp_j + 1): 70 | for j in range(len(col)): 71 | max_matrix[cnt][j] = matrix[i][j] 72 | cnt += 1 73 | 74 | if temp_i == None: 75 | return temp_max 76 | else: 77 | matrix = max_matrix 78 | -------------------------------------------------------------------------------- /곽태웅/String_Anagrams: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | from itertools import permutations 4 | temp = [] 5 | cnt = 0 6 | for i in range(len(strs)): 7 | if strs[i] != "0": 8 | if len(strs[i]) < 2: 9 | N = strs[i] 10 | else: 11 | N = list(permutations(strs[i], 2)) 12 | N.sort() 13 | temp.append([]) 14 | temp[cnt].append(strs[i]) 15 | else: 16 | continue 17 | for j in range(i+1, len(strs)): 18 | if len(strs[i]) != len(strs[j]): 19 | continue 20 | if len(strs[j]) < 2: 21 | K = strs[j] 22 | else: 23 | K = list(permutations(strs[j], 2)) 24 | K.sort() 25 | if N == K: 26 | temp[cnt].append(strs[j]) 27 | strs[j] = "0" 28 | cnt += 1 29 | return temp 30 | -------------------------------------------------------------------------------- /곽태웅/String_Log_Files: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 3 | temp_dig = [] 4 | temp_word = {} 5 | for i in logs: 6 | k = i.split(" ") 7 | if 48 <= ord(k[1][0]) <= 57: 8 | temp_dig.append(logs.index(i)) 9 | else: 10 | j = i.split(" ") 11 | temp_word["".join(j[1:])] = temp_word.get("".join(j[1:]), []) + [logs.index(i)] 12 | temp_word = sorted(temp_word.items()) 13 | answer = [] 14 | for i in range(len(temp_word)): 15 | temp_w ={} 16 | if len(temp_word[i][1]) > 1: 17 | for k in range(len(temp_word[i][1])): 18 | temp_w[logs[temp_word[i][1][k]].split(" ")[0]] = temp_word[i][1][k] 19 | temp_w = sorted(temp_w.items()) 20 | for k in range(len(temp_w)): 21 | answer.append(logs[temp_w[k][1]]) 22 | else: 23 | answer.append(logs[temp_word[i][1][0]]) 24 | 25 | for i in range(len(temp_dig)): 26 | answer.append(logs[temp_dig[i]]) 27 | return answer 28 | 29 | -------------------------------------------------------------------------------- /곽태웅/Top K Frequent Element: -------------------------------------------------------------------------------- 1 | 1차 시도 실패 -이해가 안됨 2 | ==================================================== 3 | class Solution: 4 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 5 | temp1 = [] 6 | temp2 = [] 7 | res =[] 8 | #temp1 => 값이 몇갠지 판단 / temp2 => 해당 값 9 | for i in nums: #여기 왜 남은 것들은 안들어가지지? 10 | temp1.append(nums.count(i)) 11 | temp2.append(i) 12 | while i in nums: 13 | nums.remove(i) 14 | 15 | for _ in range(k): 16 | res.append(temp2[temp1.index(max(temp1))]) 17 | temp1[temp1.index(max(temp1))] = 0 18 | 19 | return res 20 | ==================================================== 21 | 22 | 2차 시도 실패 - 타임 아웃 23 | ==================================================== 24 | class Solution: 25 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 26 | temp1 = [] 27 | temp2 = [] 28 | res =[] 29 | #temp1 => 값이 몇갠지 판단 / temp2 => 해당 값 30 | for i in nums[:]: #여기 왜 남은 것들은 안들어가지지? 31 | temp1.append(nums.count(i)) 32 | temp2.append(i) 33 | while i in nums: 34 | nums.remove(i) 35 | 36 | for _ in range(k): 37 | res.append(temp2[temp1.index(max(temp1))]) 38 | temp1[temp1.index(max(temp1))] = 0 39 | 40 | return res 41 | ==================================================== 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /곽태웅/hanoi: -------------------------------------------------------------------------------- 1 | def hanoi(n,a,b,c): 2 | global cnt 3 | cnt += 1 4 | if n == 1: print(str(a) + "->" + str(c)) 5 | else: 6 | hanoi(n-1,a,c,b) 7 | print(str(a) + "->" + str(c)) 8 | hanoi(n-1,b,a,c) 9 | 10 | 11 | n = int(input()) 12 | cnt = 0 13 | hanoi(n, 1, 2, 3) 14 | print(cnt) 15 | -------------------------------------------------------------------------------- /곽태웅/leetcode_1: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 8 | 9 | if head == None: 10 | return head 11 | 12 | cur = head 13 | cnt = 1 14 | while cur.next != None: 15 | cnt += 1 16 | cur = cur.next 17 | 18 | kk = k % cnt 19 | 20 | if kk == 0: 21 | return head 22 | else: 23 | for i in range(kk): 24 | cur = head 25 | while cur.next != None: 26 | tmp = cur 27 | cur = cur.next 28 | 29 | tmp_end = cur 30 | tmp_fnt = head 31 | head = tmp_end 32 | head.next = tmp_fnt 33 | tmp.next = None 34 | 35 | return head 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /곽태웅/leetcode_2: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: ListNode) -> ListNode: 8 | if head == None: return head 9 | 10 | cur = head 11 | tmp_cur = cur.next 12 | be_cur = None 13 | 14 | while cur.next != None: 15 | if cur.val == tmp_cur.val: 16 | while cur.val == tmp_cur.val: 17 | if tmp_cur.next != None: tmp_cur = tmp_cur.next 18 | else: 19 | if cur.val == head.val: 20 | head = None 21 | return head 22 | else: 23 | be_cur.next = None 24 | return head 25 | 26 | if cur.val == head.val: 27 | head = tmp_cur 28 | cur = tmp_cur 29 | tmp_cur = cur.next 30 | else: 31 | be_cur.next = tmp_cur 32 | cur = tmp_cur 33 | tmp_cur = cur.next 34 | 35 | else: 36 | be_cur = cur 37 | cur = cur.next 38 | tmp_cur = cur.next 39 | 40 | return head 41 | -------------------------------------------------------------------------------- /곽태웅/쇠막대기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(inp): 2 | cnt_st, answer = 0, 0 3 | top = '' 4 | for i in inp: 5 | if i == '(': 6 | cnt_st += 1 7 | answer += 1 8 | elif i == ')': 9 | if top == '(': 10 | cnt_st -= 1 11 | answer -= 1 12 | answer += cnt_st 13 | else: 14 | cnt_st -= 1 15 | top = i 16 | 17 | return answer 18 | 19 | print(solution(input())) 20 | 21 | ## 수정 0802, 23:23 22 | ## 수정 0802, 23:48 23 | -------------------------------------------------------------------------------- /곽태웅/주식문제/solution.py: -------------------------------------------------------------------------------- 1 | def solution(prices): 2 | answer = [] 3 | cnt = 1 4 | for i in prices: 5 | stop_temp = 0 6 | for j in range(cnt, len(prices)): 7 | if int(i) > int(prices[j]): 8 | answer.append(j - cnt + 1) 9 | stop_temp = 1 10 | break 11 | if stop_temp == 0: 12 | answer.append(len(prices) - cnt) 13 | cnt += 1 14 | 15 | return answer 16 | -------------------------------------------------------------------------------- /김인호/(그래프)Course Schedule/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # 위상정렬 4 | class Solution: 5 | def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 6 | v, e = numCourses, len(prerequisites) 7 | graph = [[] for i in range(v)] 8 | indegree = [0] * v 9 | 10 | for i in range(e): 11 | a, b = prerequisites[i] 12 | graph[b].append(a) 13 | indegree[a] += 1 14 | 15 | result = [] 16 | dq = deque() 17 | 18 | for i in range(v): 19 | if indegree[i] == 0: 20 | dq.append(i) 21 | 22 | while dq: 23 | now = dq.popleft() 24 | result.append(now) 25 | 26 | for i in graph[now]: 27 | indegree[i] -= 1 28 | if indegree[i] == 0: 29 | dq.append(i) 30 | 31 | if len(result) == numCourses: 32 | return True 33 | else: 34 | return False -------------------------------------------------------------------------------- /김인호/(그래프)Is Graph Bipartite/solution.py: -------------------------------------------------------------------------------- 1 | # bipartite 그래프 : 다른 그룹의 정점이 간선으로 연결되어져 있는(<=> 같은 그룹에 속한 정점끼리는 서로 인접하지 않도록 하는) 그래프 2 | from collections import deque 3 | 4 | class Solution: 5 | def isBipartite(self, graph: List[List[int]]) -> bool: 6 | visited = [0] * len(graph) 7 | 8 | for v in range(len(graph)): 9 | if not visited[v]: 10 | # 아래부턴 BFS 코드 11 | dq = deque([v]) 12 | visited[v] = 1 13 | 14 | while dq: 15 | idx = dq.popleft() 16 | 17 | for i in graph[idx]: 18 | if visited[i] == 0: 19 | visited[i] = visited[idx] * -1 20 | dq.append(i) 21 | elif visited[i] == visited[idx]: 22 | return False 23 | return True -------------------------------------------------------------------------------- /김인호/(그래프)Keys and Rooms/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # bfs로 푼다 4 | class Solution: 5 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 6 | dq = deque([0]) 7 | seen = set([0]) 8 | while dq: 9 | i = dq.popleft() 10 | for j in rooms[i]: 11 | if j not in seen: 12 | dq.append(j) 13 | seen.add(j) 14 | if len(seen) == len(rooms): 15 | return True 16 | return len(seen) == len(rooms) -------------------------------------------------------------------------------- /김인호/(링크드리스트)Remove Duplicates/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteDuplicates(self, head: ListNode) -> ListNode: 3 | # 노드개 한개 또는 없을때 예외처리 4 | if head is None or head.next is None: 5 | return head 6 | temp = head 7 | isRemove = False 8 | # 노드 앞에서 부터 끝까지 순차 탐색 9 | while temp.next != None: 10 | # 중복 숫자가 나올시, 11 | if temp.val == temp.next.val: 12 | isRemove = True 13 | # 앞 숫자와 다른 숫자가 나올시, 14 | else: 15 | # 삭제할 숫자가 있을시, 16 | if isRemove: 17 | isRemove = False 18 | # 중복된 숫자들 다음 노드를 가리킴 19 | try: 20 | cur.next = temp.next 21 | # 리스트 처음부터 중복숫자가 나올경우, 헤드를 중복숫자 다음으로 가리킴 22 | except: 23 | head = temp.next 24 | else: 25 | # 삭제 할 노드가 없을시, 현재 노드를 커서가 가리킴 26 | cur = temp 27 | temp = temp.next 28 | # 리스트의 끝이 중복이면 따로 처리. 29 | if isRemove: 30 | try: 31 | cur.next = temp.next 32 | except: 33 | head = temp.next 34 | 35 | return head -------------------------------------------------------------------------------- /김인호/(링크드리스트)RotateList/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 8 | # 노드개 한개 또는 없을때 예외처리 9 | if head == None or head.next == None: 10 | return head 11 | temp = head 12 | length = 1 13 | # 링크드 리스트의 길이를 구한다. 14 | while temp.next != None: 15 | temp = temp.next 16 | length += 1 17 | # 반복 횟수를 줄임. 18 | k %= length 19 | if k == 0: 20 | return head 21 | for i in range(k): 22 | temp = head 23 | # 끝을 빼고 앞에다가 붙임. 24 | while True: 25 | if temp.next == None: 26 | tail.next = None 27 | temp.next = head 28 | head = temp 29 | break 30 | tail = temp 31 | temp = temp.next 32 | return head -------------------------------------------------------------------------------- /김인호/(링크드리스트)책_2-4.py/solution.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, val, next): 3 | self.val = val 4 | self.next = next 5 | 6 | # 링크드 리스트 value 와 x 값을 입력 받는다. 7 | arr = list(map(int,input().split())) 8 | x_value = int(input()) 9 | 10 | # 링크드리스트 생성 11 | h = None 12 | for i in range(len(arr)-1,-1,-1): 13 | Node(arr[i],h) 14 | h = Node(arr[i],h) 15 | 16 | temp = h 17 | print("====linked list====") 18 | while h != None: 19 | if h.next != None: 20 | print(h.val, end = ' ') 21 | else: 22 | print(h.val) 23 | h = h.next 24 | 25 | # x 노드만 빼기 26 | h = temp 27 | while True: 28 | if h.next == None: 29 | break 30 | if h.next.val == x_value: 31 | isFind = True 32 | nh = h.next 33 | h.next = h.next.next 34 | nh.next = None 35 | break 36 | h = h.next 37 | 38 | # x 노드 기준으로 작으면 왼쪽 크거나 같으면 오른쪽으로 노드들을 붙이기 39 | nt = nh 40 | while temp != None: 41 | next_node = temp.next 42 | if temp.val < x_value: 43 | temp.next = nh 44 | nh = temp 45 | else: 46 | nt.next = temp 47 | nt = temp 48 | nt.next = None 49 | temp = next_node 50 | 51 | # 새로운 링크드 리스트 출력. 52 | print("====New linked list====") 53 | while nh != None: 54 | if nh.next != None: 55 | print(nh.val, end = ' ') 56 | else: 57 | print(nh.val) 58 | nh = nh.next 59 | 60 | # 테스트 코드 61 | # 4 3 2 6 62 | # 3 63 | 64 | 65 | # 4 3 1 5 6 7 8 9 66 | # 6 67 | 68 | 69 | # 1 1 1 3 3 3 2 2 2 4 4 70 | # 3 71 | 72 | # 3 3 3 3 1 73 | # 1 -------------------------------------------------------------------------------- /김인호/(문자열)Group Anagrams/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | dic = {} 4 | ans = [] 5 | for s in strs: 6 | temp = str(sorted(list(s))) 7 | if temp in dic: 8 | dic[temp].append(s) 9 | else: 10 | dic[temp] = [s] 11 | 12 | for _,v in dic.items(): 13 | ans.append(v) 14 | 15 | return ans -------------------------------------------------------------------------------- /김인호/(문자열)Reorder Data in Log Files/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 3 | s, d = [], [] 4 | ans = [] 5 | for l in logs: 6 | i = 0 7 | while i < len(l) and l[i] != " ": 8 | i += 1 9 | identifier = l[:i] 10 | letter = l[i + 1 :] 11 | if letter[0].isalpha(): 12 | s.append((letter, l)) 13 | else: 14 | d.append(l) 15 | 16 | s.sort() 17 | 18 | for _, l in s: 19 | ans.append(l) 20 | 21 | ans.extend(d) 22 | 23 | return ans 24 | 25 | # 다른 풀이 26 | class Solution: 27 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 28 | s, d = [], [] 29 | ans = [] 30 | for l in logs: 31 | temp = l.split() 32 | if temp[1].isalpha(): 33 | s.append(l.split(maxsplit=1)) 34 | else: 35 | d.append(l) 36 | 37 | s = sorted(sorted(s, key=lambda x: x[0]), key=lambda x: x[1]) 38 | 39 | for i in s: 40 | ans.append(" ".join(i)) 41 | 42 | for i in d: 43 | ans.append(i) 44 | 45 | return ans 46 | -------------------------------------------------------------------------------- /김인호/(문자열)문자열 압축/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | 3 | length = len(s) 4 | slic = len(s) // 2 5 | 6 | for k in range(1, slic + 1): 7 | is_duplicate = False 8 | temp = "" 9 | idx = 0 10 | cnt = 1 11 | 12 | while idx + k < len(s): 13 | if s[idx : idx + k] == s[idx + k : idx + k + k]: 14 | is_duplicate = True 15 | cnt += 1 16 | else: 17 | if is_duplicate: 18 | temp = temp + str(cnt) + s[idx : idx + k] 19 | cnt = 1 20 | is_duplicate = False 21 | else: 22 | temp += s[idx : idx + k] 23 | 24 | idx += k 25 | 26 | # 마지막 부분 27 | if is_duplicate: 28 | temp = temp + str(cnt) + s[idx : idx + k] 29 | else: 30 | temp += s[idx : idx + k] 31 | 32 | length = min(length, len(temp)) 33 | 34 | return length 35 | -------------------------------------------------------------------------------- /김인호/(스택,큐)쇠막대기/solution.py: -------------------------------------------------------------------------------- 1 | # cutN : 잘린 막대기 수 2 | # num : 잘리지 않은 원래 막대기 수 3 | 4 | def solution(arrangment): 5 | arr = arrangment.replace("()", "L") 6 | cutN, num = 0, 0 7 | 8 | for i in arr: 9 | if i == "(": 10 | cutN += 1 11 | num += 1 12 | elif i == ")": 13 | num -= 1 14 | else: 15 | cutN += num 16 | print(cutN) 17 | return cutN 18 | 19 | s = input() 20 | solution(s) 21 | -------------------------------------------------------------------------------- /김인호/(스택,큐)주식가격/solution.py: -------------------------------------------------------------------------------- 1 | # 시간 복잡도 O(n2), 2 | def solution(prices): 3 | answer = [] 4 | for i in range(len(prices)): 5 | s = 0 6 | for j in range(i + 1, len(prices)): 7 | s += 1 8 | if prices[i] > prices[j]: 9 | break 10 | answer.append(s) 11 | 12 | return answer 13 | # Worst case 같은 경우 시간초과. 14 | # arr = [i for i in range(100000)] 15 | solution(arr) 16 | -------------------------------------------------------------------------------- /김인호/(스택,큐)책_3-4.py/solution.py: -------------------------------------------------------------------------------- 1 | MSG_FORMAT = "{}번 원반을 {}에서 {}로 이동" 2 | 3 | def move(N, start, to): 4 | temp = dic[start].pop() 5 | dic[to].append(temp) 6 | print(MSG_FORMAT.format(N, start, to)) 7 | 8 | 9 | def hanoi(N, start, to, via): 10 | if N == 1: 11 | move(1, start, to) 12 | else: 13 | hanoi(N - 1, start, via, to) 14 | move(N, start, to) 15 | hanoi(N - 1, via, to, start) 16 | 17 | N = int(input()) 18 | dic = {} 19 | dic["A"] = [i for i in range(N, 0, -1)] 20 | dic["B"], dic["C"] = [], [] 21 | 22 | hanoi(N, "A", "C", "B") 23 | print("마지막 탑 :", dic["C"]) 24 | -------------------------------------------------------------------------------- /김인호/(재귀)K-th Symbol in Grammar/K-th Symbol in Grammar.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthGrammar(self, N: int, K: int) -> int: 3 | if N == 1: 4 | return 0 5 | 6 | # 짝수 번째 숫자일때 7 | if K % 2 == 0: 8 | if self.kthGrammar(N - 1, K // 2) == 0: 9 | return 1 10 | else: 11 | return 0 12 | else: 13 | # 홀수 번째 숫자일때 14 | if self.kthGrammar(N - 1, (K + 1) // 2) == 0: 15 | return 0 16 | else: 17 | return 1 18 | 19 | 20 | # 써가면서 패턴 파악. N row의 K번째 숫자가 N-1 row의 몇번째 숫자에서 나왔는지 파악한다. 21 | 22 | # row1 : 0 23 | # row2 : 01 24 | # row3 : 0110 25 | # row4 : 0110 1001 26 | # row5 : 0110 1001 1001 0110 27 | # row6 : 0110 1001 1001 0110 1001 0110 0110 1001 28 | # row7 : 0110 1001 1001 0110 1001 0110 0110 1001 1001 0110 0110 1001 0110 1001 1001 0110 -------------------------------------------------------------------------------- /김인호/(큐)Design Circular Queue/solution.py: -------------------------------------------------------------------------------- 1 | class MyCircularQueue: 2 | def __init__(self, k: int): 3 | """ 4 | Initialize your data structure here. Set the size of the queue to be k. 5 | """ 6 | self.size = k + 1 7 | self.rear = 0 8 | self.front = 0 9 | self.cq = [-1] * (self.size) 10 | 11 | def enQueue(self, value: int) -> bool: 12 | """ 13 | Insert an element into the circular queue. Return true if the operation is successful. 14 | """ 15 | if self.isFull(): 16 | return False 17 | else: 18 | self.rear = (self.rear + 1) % self.size 19 | self.cq[self.rear] = value 20 | return True 21 | 22 | def deQueue(self) -> bool: 23 | """ 24 | Delete an element from the circular queue. Return true if the operation is successful. 25 | """ 26 | if self.isEmpty(): 27 | return False 28 | else: 29 | self.front = (self.front + 1) % self.size 30 | return True 31 | 32 | def Front(self) -> int: 33 | """ 34 | Get the front item from the queue. 35 | """ 36 | if self.isEmpty(): 37 | return -1 38 | else: 39 | return self.cq[(self.front + 1) % self.size] 40 | 41 | def Rear(self) -> int: 42 | """ 43 | Get the last item from the queue. 44 | """ 45 | if self.isEmpty(): 46 | return -1 47 | else: 48 | return self.cq[self.rear] 49 | 50 | def isEmpty(self) -> bool: 51 | """ 52 | Checks whether the circular queue is empty or not. 53 | """ 54 | if self.rear == self.front: 55 | return True 56 | return False 57 | 58 | def isFull(self) -> bool: 59 | """ 60 | Checks whether the circular queue is full or not. 61 | """ 62 | if (self.rear + 1) % self.size == self.front: 63 | return True 64 | return False 65 | -------------------------------------------------------------------------------- /김인호/(큐)Max Sum of Rectangle No Larger Than K/solution.py: -------------------------------------------------------------------------------- 1 | # 시간 통과 x, 이진 탐색 x 2 | class Solution: 3 | def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: 4 | if not matrix or not matrix[0]: 5 | return 0 6 | N, M = len(matrix), len(matrix[0]) 7 | ans = float("-inf") 8 | dp = [[0]*M for _ in range(N)] 9 | 10 | for i in range(N): 11 | for j in range(M): 12 | total = matrix[i][j] 13 | if i>0: 14 | total += dp[i-1][j] 15 | if j>0: 16 | total += dp[i][j-1] 17 | if i>0 and j>0: 18 | total -= dp[i-1][j-1] 19 | dp[i][j] = total 20 | 21 | for r in range(i+1): 22 | for c in range(j+1): 23 | temp = dp[i][j] 24 | if r > 0: 25 | temp -= dp[r-1][j] 26 | if c > 0: 27 | temp -= dp[i][c-1] 28 | if r > 0 and c > 0: 29 | temp += dp[r-1][c-1] 30 | if temp<=k: 31 | ans = max(temp,ans) 32 | return ans 33 | 34 | 35 | # 시간 통과 코드 36 | class Solution(object): 37 | def maxSumSubmatrix(self, matrix, k): 38 | """ 39 | :type matrix: List[List[int]] 40 | :type k: int 41 | :rtype: int 42 | """ 43 | m = len(matrix) 44 | n = len(matrix[0]) if m else 0 45 | 46 | M = max(m, n) 47 | N = min(m, n) 48 | ans = -1e9 49 | for x in range(N): 50 | sums = [0] * M 51 | for y in range(x, N): 52 | slist, num = [], 0 53 | for z in range(M): 54 | sums[z] += matrix[z][y] if m > n else matrix[y][z] 55 | num += sums[z] 56 | if num <= k: 57 | ans = max(ans, num) 58 | i = bisect.bisect_left(slist, num-k) 59 | # i값이 slist의 맨끝이 아니면 즉, num이 젤 크지 않다면 60 | if i != len(slist): 61 | ans = max(ans, num - slist[i]) 62 | bisect.insort(slist, num) 63 | return ans -------------------------------------------------------------------------------- /김인호/(해시)Longest Substring Without Repeating Characters/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s) -> int: 3 | # i 는 길이를 세기 시작하는 시작하는 idx 4 | i = 0 5 | ans = 0 6 | char_dict = {} 7 | 8 | for j in range(len(s)): 9 | # 현재 문자인 s[j]가 이미 dict에 있고 10 | # 현재 문자와 같은 문자인 char_dict[s[j]]가 i보다 크거나 같으면 11 | # i를 char_dict[s[j]] 보다 1 큰수로 하여 중복을 없앤 범위로 갱신한다. 12 | # 그렇지 않은 경우(중복이 없는 경우), ans를 갱신한다. 13 | if s[j] in char_dict and i <= char_dict[s[j]]: 14 | i = char_dict[s[j]] + 1 15 | else: 16 | ans = max(ans, j - i + 1) 17 | 18 | char_dict[s[j]] = j 19 | 20 | return ans 21 | -------------------------------------------------------------------------------- /김인호/(해시)Top K Frequent Elements/solution.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 5 | heap, ans = [], [] 6 | key, dic = [], {} 7 | for i in nums: 8 | if i in dic: 9 | # 나온 횟수를 저장. 10 | dic[i] += 1 11 | else: 12 | dic[i] = 1 13 | # dict의 key 리스트 저장. 14 | key.append(i) 15 | for i in key: 16 | # 큐에서 횟수가 큰 순서대로 먼저 나오게 하기 위해서 -를 붙임. 17 | heapq.heappush(heap, (-dic[i], i)) 18 | 19 | for i in range(k): 20 | # 횟수가 큰 수의 숫자를 ans에 담는다. 21 | _, v = heapq.heappop(heap) 22 | ans.append(v) 23 | 24 | return ans 25 | 26 | -------------------------------------------------------------------------------- /백승연/Hash-longest substring/solution.py: -------------------------------------------------------------------------------- 1 | #모범답안 2 | 3 | 4 | class Solution: 5 | def lengthOfLongestSubstring(self, s): 6 | arr = {} 7 | start = 0 8 | length = 0 9 | 10 | for index, char in enumerate(s): 11 | if char in arr and start <= arr[char]: 12 | start = arr[char] + 1 13 | else: 14 | length = max(length, index - start + 1) 15 | 16 | arr[char] = index 17 | 18 | return length 19 | 20 | 21 | s1 = Solution() 22 | 23 | print(s1.lengthOfLongestSubstring('abcdae')) 24 | -------------------------------------------------------------------------------- /백승연/Hash-top k frequent elements/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | res = [] 4 | ht = dict() 5 | 6 | for i in nums: 7 | ht[i] = ht.get(i, 0) + 1 8 | 9 | max = 0 10 | 11 | for i in range(k): 12 | for j in ht.keys(): 13 | if max < ht.get(j): 14 | max = ht.get(j) 15 | maxkey = j 16 | res.append(maxkey) 17 | del ht[maxkey] 18 | max = 0 19 | 20 | return res 21 | -------------------------------------------------------------------------------- /백승연/Hash-top k frequent elements/solution2.py: -------------------------------------------------------------------------------- 1 | # 카운터 모듈 사용 2 | 3 | from collections import Counter 4 | 5 | 6 | class Solution: 7 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 8 | 9 | freqs = Counter(nums).most_common(k) 10 | return list(zip(*freqs))[0] 11 | -------------------------------------------------------------------------------- /백승연/Queue-Design Circular Queue/solution.py: -------------------------------------------------------------------------------- 1 | class MyCircularQueue: 2 | 3 | def __init__(self, k: int): 4 | """ 5 | Initialize your data structure here. Set the size of the queue to be k. 6 | """ 7 | self.Q = [-1] * k 8 | self.size = k 9 | self.front = -1 10 | self.rear = -1 11 | 12 | def enQueue(self, value: int) -> bool: 13 | """ 14 | Insert an element into the circular queue. Return true if the operation is successful. 15 | """ 16 | # Q: full 17 | if self.isFull(): 18 | return False 19 | 20 | # Q: empty 21 | elif self.isEmpty(): 22 | self.front = 0 23 | self.rear = 0 24 | self.Q[self.rear] = value 25 | return True 26 | 27 | else: 28 | self.rear = (self.rear + 1) % self.size 29 | self.Q[self.rear] = value 30 | return True 31 | 32 | def deQueue(self) -> bool: 33 | """ 34 | Delete an element from the circular queue. Return true if the operation is successful. 35 | """ 36 | #Q : empty 37 | if self.isEmpty(): 38 | return False 39 | 40 | #Q : one element left 41 | elif self.front == self.rear: 42 | self.front = -1 43 | self.rear = -1 44 | return True 45 | else: 46 | self.front = (self.front + 1) % self.size 47 | return True 48 | 49 | def Front(self) -> int: 50 | """ 51 | Get the front item from the queue. 52 | """ 53 | if self.front == -1: 54 | return -1 55 | else: 56 | return self.Q[self.front] 57 | 58 | def Rear(self) -> int: 59 | """ 60 | Get the last item from the queue. 61 | """ 62 | if self.rear == -1: 63 | return -1 64 | else: 65 | return self.Q[self.rear] 66 | 67 | def isEmpty(self) -> bool: 68 | """ 69 | Checks whether the circular queue is empty or not. 70 | """ 71 | if self.rear == self.front == -1: 72 | return True 73 | else: 74 | return False 75 | 76 | def isFull(self) -> bool: 77 | """ 78 | Checks whether the circular queue is full or not. 79 | """ 80 | 81 | # if all(x!= -1 for x in self.Q): 82 | # return True 83 | length = abs(self.rear-self.front) + 1 84 | if length == self.size: 85 | return True 86 | else: 87 | return False 88 | 89 | 90 | 91 | # Your MyCircularQueue object will be instantiated and called as such: 92 | # obj = MyCircularQueue(k) 93 | # param_1 = obj.enQueue(value) 94 | # param_2 = obj.deQueue() 95 | # param_3 = obj.Front() 96 | # param_4 = obj.Rear() 97 | # param_5 = obj.isEmpty() 98 | # param_6 = obj.isFull() -------------------------------------------------------------------------------- /백승연/Queue-Printer/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | def solution(priorities, location): 5 | answer = 0 6 | 7 | Q = [(pos, val) for pos, val in enumerate(deque(priorities))] 8 | Q = deque(Q) 9 | 10 | while Q: 11 | cur = Q.popleft() 12 | if any(cur[1] < x[1] for x in Q): 13 | Q.append(cur) 14 | continue 15 | answer += 1 16 | if cur[0] == location: 17 | break 18 | 19 | return answer -------------------------------------------------------------------------------- /백승연/Stack- Hanoi/solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 1번 탑 n-1개 원판 -> mid로 옮김 3 | 1번 탑 마지막 원판 -> dest 로 옮김 4 | 2번 탑 n-1개 원판 -> dest로 옮김 5 | ''' 6 | 7 | 8 | def hanoi(n, start, mid, dest): 9 | if n == 1: 10 | print(start, 'move to', dest) 11 | return 12 | hanoi(n - 1, start, dest, mid) 13 | hanoi(1, start, mid, dest) 14 | hanoi(n - 1, mid, start, dest) 15 | 16 | 17 | hanoi(3, '1번', '2번', '3번') 18 | -------------------------------------------------------------------------------- /백승연/쇠막대기/solution.py: -------------------------------------------------------------------------------- 1 | inp = input() 2 | stack = [] 3 | cnt = 0 4 | 5 | for i in range(len(inp)): 6 | if inp[i] == '(': 7 | stack.append(inp[i]) 8 | else: 9 | if inp[i - 1] == '(': 10 | stack.pop() 11 | cnt += len(stack) 12 | else: 13 | stack.pop() 14 | cnt += 1 15 | print(cnt) -------------------------------------------------------------------------------- /백승연/주식가격/solution.py: -------------------------------------------------------------------------------- 1 | prices = list(map(str, input().split(','))) 2 | prices = list(map(int, prices)) 3 | 4 | 5 | # 시간초과 6 | # def solution(prices): 7 | # answer = [] 8 | # 9 | # for i in range(len(prices)): 10 | # cnt = 0 11 | # stack = prices[i + 1:] 12 | # while stack and stack[-1] >= prices[i]: 13 | # cnt += 1 14 | # stack.pop() 15 | # answer.append(cnt) 16 | # return answer 17 | 18 | 19 | #프로그래머스 풀이 20 | def solution(prices): 21 | answer = [0] * len(prices) 22 | for i in range(len(prices)): 23 | for j in range(i + 1, len(prices)): 24 | if prices[i] <= prices[j]: 25 | answer[i] += 1 26 | else: 27 | answer[i] += 1 28 | break 29 | return answer 30 | 31 | 32 | print(solution(prices)) 33 | -------------------------------------------------------------------------------- /송민수/622. Design Circular Queue: -------------------------------------------------------------------------------- 1 | class MyCircularQueue: 2 | 3 | def __init__(self, k: int): 4 | self.q=[None]*k 5 | self.max_len=k 6 | self.front_p=0 7 | self.rear_p=0 8 | 9 | def enQueue(self, value: int) -> bool: 10 | if self.q[self.rear_p] is None: 11 | self.q[self.rear_p] = value 12 | self.rear_p=(self.rear_p+1)%self.max_len 13 | return True 14 | else: 15 | return False 16 | 17 | def deQueue(self) -> bool: 18 | if self.q[self.front_p] is None: 19 | return False 20 | else: 21 | self.q[self.front_p] = None 22 | self.front_p = (self.front_p+1)%self.max_len 23 | return True 24 | 25 | def Front(self) -> int: 26 | if self.q[self.front_p] is None: 27 | return -1 28 | else: 29 | return self.q[self.front_p] 30 | 31 | def Rear(self) -> int: 32 | if self.q[self.rear_p-1] is None: 33 | return -1 34 | else: 35 | return self.q[self.rear_p-1] 36 | 37 | def isEmpty(self) -> bool: 38 | return self.front_p==self.rear_p and self.q[self.front_p] is None 39 | 40 | def isFull(self) -> bool: 41 | return self.front_p==self.rear_p and self.q[self.front_p] is not None 42 | 43 | 44 | # Your MyCircularQueue object will be instantiated and called as such: 45 | # obj = MyCircularQueue(k) 46 | # param_1 = obj.enQueue(value) 47 | # param_2 = obj.deQueue() 48 | # param_3 = obj.Front() 49 | # param_4 = obj.Rear() 50 | # param_5 = obj.isEmpty() 51 | # param_6 = obj.isFull() 52 | -------------------------------------------------------------------------------- /송민수/hanoi: -------------------------------------------------------------------------------- 1 | def hanoi(n,left,mid,right,answer): 2 | if n==1: 3 | return answer.append([left,right]) 4 | hanoi(n-1,left,right,mid,answer) 5 | answer.append([left,right]) 6 | hanoi(n-1,mid,left,right,answer) 7 | 8 | def solution(n): 9 | answer=[] 10 | hanoi(n,1,2,3,answer) 11 | return answer 12 | -------------------------------------------------------------------------------- /송민수/leetcode 779.py: -------------------------------------------------------------------------------- 1 | def kthGrammar(n,k): 2 | if n==1: 3 | return 0 4 | if (k%2==0): 5 | return 1 if kthGrammar(n-1,k/2)==0 else 0 6 | else: 7 | return 0 if kthGrammar(n-1,(k+1)/2)==0 else 1 8 | 9 | print(kthGrammar(1,1)) 10 | print(kthGrammar(2,1)) 11 | print(kthGrammar(2,2)) 12 | print(kthGrammar(4,5)) 13 | 14 | 15 | -------------------------------------------------------------------------------- /송민수/프로그래머스-쇠막대기.py: -------------------------------------------------------------------------------- 1 | def solution(arrangement): 2 | stack=[] 3 | line=0 4 | for i in range(len(arrangement)): 5 | if arrangement[i]=='(': 6 | stack.append('(') 7 | elif arrangement[i]==')': 8 | if arrangement[i-1]=='(': 9 | line+=(len(stack)-1) 10 | else: 11 | line+=1 12 | stack.pop() 13 | # print(stack,line) 14 | 15 | return line 16 | 17 | print(solution('()(((()())(())()))(()) ')) 18 | -------------------------------------------------------------------------------- /송민수/프로그래머스-주식가격.py: -------------------------------------------------------------------------------- 1 | def solution(prices): 2 | answer = [] 3 | for i in range(len(prices)): 4 | cnt=0 5 | for j in range(i+1,len(prices)): 6 | if prices[i]<=prices[j]: 7 | cnt+=1 8 | elif prices[i]>prices[j]: 9 | cnt+=1 10 | break 11 | answer.append(cnt) 12 | 13 | return answer 14 | 15 | print(solution([1, 2, 3, 2, 3])) 16 | -------------------------------------------------------------------------------- /안형욱/design-circular-queue/solution.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/design-circular-queue/ 2 | 3 | class MyCircularQueue: 4 | 5 | def __init__(self, k: int): 6 | """ 7 | Initialize your data structure here. Set the size of the queue to be k. 8 | """ 9 | self.size = k 10 | self.data = [] 11 | 12 | def enQueue(self, value: int) -> bool: 13 | """ 14 | Insert an element into the circular queue. Return true if the operation is successful. 15 | """ 16 | if self.isFull(): 17 | return False 18 | self.data.append(value) 19 | return True 20 | 21 | def deQueue(self) -> bool: 22 | """ 23 | Delete an element from the circular queue. Return true if the operation is successful. 24 | """ 25 | if self.isEmpty(): 26 | return False 27 | self.data = self.data[1:] 28 | return True 29 | 30 | def Front(self) -> int: 31 | """ 32 | Get the front item from the queue. 33 | """ 34 | return -1 if self.isEmpty() else self.data[0] 35 | 36 | def Rear(self) -> int: 37 | """ 38 | Get the last item from the queue. 39 | """ 40 | return -1 if self.isEmpty() else self.data[-1] 41 | 42 | def isEmpty(self) -> bool: 43 | """ 44 | Checks whether the circular queue is empty or not. 45 | """ 46 | return not len(self.data) 47 | 48 | def isFull(self) -> bool: 49 | """ 50 | Checks whether the circular queue is full or not. 51 | """ 52 | return len(self.data)==self.size 53 | -------------------------------------------------------------------------------- /안형욱/hanoi-top/solution.py: -------------------------------------------------------------------------------- 1 | def Hanoi(n): 2 | if n==1: 3 | return 1 4 | return 2*Hanoi(n-1)+1 5 | 6 | def printOrder(disk, start, mid, end): 7 | if disk == 1: 8 | print(start, end) 9 | else: 10 | printOrder(disk-1, start, end, mid) 11 | print(start, end) 12 | printOrder(disk-1, mid, start, end) 13 | 14 | n = int(input()) 15 | disk = n 16 | print(Hanoi(n)) 17 | printOrder(disk, 1, 2, 3) -------------------------------------------------------------------------------- /안형욱/remove-duplicates-from-sorted-list-ii/solution.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/submissions/ 2 | 3 | # Definition for singly-linked list. 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | class Solution: 10 | def deleteDuplicates(self, head: ListNode) -> ListNode: 11 | targetNode = head 12 | temp = pre = ListNode() 13 | temp.next = targetNode 14 | 15 | while targetNode and targetNode.next: 16 | if targetNode.val == targetNode.next.val: 17 | while targetNode and targetNode.next and targetNode.val == targetNode.next.val: 18 | targetNode = targetNode.next 19 | targetNode = targetNode.next 20 | pre.next = targetNode 21 | else: 22 | pre = pre.next 23 | targetNode = targetNode.next 24 | 25 | return temp.next -------------------------------------------------------------------------------- /안형욱/rotate-list/solution.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rotate-list/ 2 | 3 | # Definition for singly-linked list. 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | class Solution: 10 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 11 | if head == None or head.next==None: 12 | return head 13 | targetNode = head 14 | count = 1 15 | while True: 16 | if targetNode.next == None: 17 | targetNode.next=head 18 | k = k%count 19 | break 20 | targetNode = targetNode.next 21 | count+=1 22 | for _ in range(count-k): 23 | head = head.next 24 | targetNode = head 25 | for _ in range(count-1): 26 | targetNode = targetNode.next 27 | targetNode.next = None 28 | return head -------------------------------------------------------------------------------- /안형욱/쇠막대기/solution.py: -------------------------------------------------------------------------------- 1 | # https://programmers.co.kr/learn/courses/30/lessons/42585 2 | 3 | def solution(arrangement): 4 | answer = 0 5 | stick = 0 6 | # ()을 0으로 바꾸어 레이저로 인식 7 | arrangement = arrangement.replace('()', '0') 8 | 9 | while len(arrangement): 10 | target = arrangement.pop() 11 | if target == '0': 12 | answer += stick 13 | elif target == '(': 14 | stick += 1 15 | elif target == ')': 16 | answer += 1 17 | stick -= 1 18 | # for i in arrangement: 19 | # if i=='0': 20 | # answer+=stick 21 | # elif i=='(': 22 | # stick+=1 23 | # elif i==')': 24 | # answer+=1 25 | # stick-=1 26 | return answer 27 | 28 | 29 | # 밑에 solution은 테스트 케이스 통과하지 못하는 부분이 있는데 왜 30 | # 그런지 모르겠네요... 같이 의논해보고 싶어서 남겨뒀습니다. 31 | # def solution(arrangement): 32 | # answer = 0 33 | # stick = 0 34 | # laser = 0 35 | # arrangement = arrangement.replace('()', '0') 36 | # for i in arrangement: 37 | # if stick and i=='0': 38 | # laser+=1 39 | # elif i=='(': 40 | # stick+=1 41 | # elif i==')': 42 | # answer+=stick*laser+1 43 | # stick-=1 44 | # laser=0 45 | # return answer 46 | -------------------------------------------------------------------------------- /안형욱/주식가격/solution.py: -------------------------------------------------------------------------------- 1 | # https://programmers.co.kr/learn/courses/30/lessons/42584 2 | 3 | def solution(prices): 4 | answer = [] 5 | n = len(prices) 6 | for i in range(n): 7 | target = prices[i] 8 | count = 0 9 | flag = False 10 | for j in range(i+1, n): 11 | if prices[j] prices[j]: 16 | break 17 | result[i] = sum 18 | return result -------------------------------------------------------------------------------- /이하은/2_linked_list/2.4_sorted_linked_list.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jeoungseungho/python-coding-study/431e02d12d0834c71f423471701a2182f66a3776/이하은/2_linked_list/2.4_sorted_linked_list.py -------------------------------------------------------------------------------- /이하은/2_linked_list/remove_duplicates_from_list.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 3 | ''' 4 | # Definition for singly-linked list. 5 | class ListNode: 6 | def __init__(self, val=0, next=None): 7 | self.val = val 8 | self.next = next 9 | 10 | class Solution(): 11 | def delete_node(self,curr): 12 | pass 13 | 14 | def deleteDuplicates(self, head: ListNode) -> ListNode: 15 | # list만들어서 해당하는 index 새로운 list node만듬 16 | prev = None 17 | curr = head 18 | 19 | while curr and curr.next: 20 | if curr.val != curr.next.val: 21 | prev = curr 22 | curr = curr.next 23 | else: 24 | while curr.next and curr.val == curr.next.val: 25 | curr = curr.next 26 | 27 | curr = curr.next 28 | if prev: 29 | prev.next = curr 30 | else: 31 | head= curr 32 | 33 | return head 34 | 35 | def print_linked_list(self,head): 36 | curr = head 37 | while curr !=None: 38 | print(curr.val) 39 | curr = curr.next 40 | 41 | def insert(self,data_list): 42 | pass 43 | 44 | # a = ListNode(1) 45 | # b = ListNode(2) 46 | # c =ListNode(2) 47 | # d = ListNode(2) 48 | # e = ListNode(3) 49 | # 50 | # a.next = b 51 | # b.next = c 52 | # c.next = d 53 | # d.next = e 54 | # 55 | # sol = Solution() 56 | # 57 | # sol_list = sol.deleteDuplicates(a) 58 | # sol.print_linked_list(sol_list) 59 | -------------------------------------------------------------------------------- /이하은/2_linked_list/rotate_list.py: -------------------------------------------------------------------------------- 1 | ''' 2 | https://leetcode.com/problems/rotate-list/ 3 | ''' 4 | 5 | class ListNode(): 6 | def __init__(self,val): 7 | self.val = val 8 | self.next = None 9 | 10 | class Solution: 11 | 12 | def changeList(self,head): 13 | 14 | curr = head 15 | prev = None 16 | while curr.next != None: 17 | prev = curr 18 | curr = curr.next 19 | 20 | new_head = curr 21 | new_head.next = head 22 | prev.next = None 23 | 24 | return new_head 25 | 26 | def read(self,head): 27 | curr = head 28 | while curr != None: 29 | print(curr.val) 30 | curr = curr.next 31 | 32 | def rotateRight(self,head:ListNode,k:int)->ListNode: 33 | 34 | for _ in range(k): 35 | head = self.changeList(head) 36 | # self.read(head) 37 | return head 38 | 39 | # 40 | # a = ListNode(1) 41 | # b = ListNode(2) 42 | # c =ListNode(3) 43 | # d = ListNode(4) 44 | # e = ListNode(5) 45 | # 46 | # a.next = b 47 | # b.next = c 48 | # c.next = d 49 | # d.next = e 50 | # 51 | # sol = Solution() 52 | # sol.rotateRight(a,2) 53 | -------------------------------------------------------------------------------- /정승호/0만들기/solution.py: -------------------------------------------------------------------------------- 1 | test_case = int(input()) 2 | answer = [] 3 | 4 | def dfs(arr, index, susik1, susik2): 5 | if index == (len(arr)-1): 6 | susik1 += str(arr[index]) 7 | susik2 += str(arr[index]) 8 | n = int(eval(susik1)) 9 | if n == 0: 10 | answer.append(susik2) 11 | else: 12 | dfs(arr, index+1, susik1 + str(arr[index]),susik2 + str(arr[index])+ " " ) 13 | dfs(arr, index+1, susik1 + str(arr[index])+'+',susik2 + str(arr[index])+'+') 14 | dfs(arr, index+1, susik1 + str(arr[index])+'-', susik2 + str(arr[index])+'-') 15 | 16 | for _ in range(test_case): 17 | n = int(input()) 18 | arr = [i for i in range(1, n+1)] 19 | dfs(arr,0,"","") 20 | for i in answer: 21 | print(i) 22 | print() 23 | answer.clear() 24 | -------------------------------------------------------------------------------- /정승호/124_나라의_숫자/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = '' 3 | while n != 0: 4 | n-=1 5 | answer = '124'[n%3] + answer 6 | n //= 3 7 | return answer 8 | -------------------------------------------------------------------------------- /정승호/2016/solution.py: -------------------------------------------------------------------------------- 1 | def solution(a, b): 2 | week = ['FRI', 'SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU'] 3 | month = [31,29,31, 30, 31, 30,31, 31, 30, 31, 30, 31] 4 | total = 0 5 | 6 | for i in range(a-1): 7 | total += month[i] 8 | total += b-1 9 | 10 | answer = week[total%7] 11 | 12 | return answer 13 | -------------------------------------------------------------------------------- /정승호/3Sum/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | result = [] 4 | nums.sort() 5 | 6 | for i in range(len(nums) - 2): 7 | # 중복값 건너뛰기 8 | if i > 0 and nums[i] == nums[i-1]: 9 | continue 10 | 11 | # 간격 좁히면서 sum 계산 12 | left, right = i+1, len(nums)-1 13 | while left < right: 14 | answer = nums[i] + nums[left] + nums[right] 15 | if answer < 0 : 16 | left += 1 17 | elif answer > 0: 18 | right -= 1 19 | else : 20 | # 정답 및 스킵처리 21 | result.append((nums[i], nums[left], nums[right])) 22 | 23 | while left < right and nums[left] == nums[left + 1]: 24 | left += 1 25 | while left < right and nums[right] == nums[right - 1]: 26 | right -= 1 27 | left += 1 28 | right -= 1 29 | 30 | return result 31 | 32 | -------------------------------------------------------------------------------- /정승호/3진법_뒤집기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = 0 3 | temp = [] 4 | 5 | while n : 6 | temp.append(str(n%3)) 7 | n = int(n/3) 8 | 9 | digit = 1 10 | for i in reversed(temp): 11 | answer += int(i)*digit 12 | digit *= 3 13 | 14 | return answer 15 | -------------------------------------------------------------------------------- /정승호/AC/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = sys.stdin.readline 5 | T = int(input()) 6 | 7 | for _ in range(T): 8 | p = input().rstrip() 9 | n = int(input()) 10 | arr = deque(input().rstrip()[1:-1].split(',')) 11 | reverse_flag = False 12 | zero_len_flag = False 13 | 14 | if n == 0: 15 | arr = deque() 16 | 17 | for ch in p: 18 | if ch == 'R': 19 | reverse_flag = not reverse_flag 20 | elif ch == 'D': 21 | if len(arr) == 0: 22 | zero_len_flag = True 23 | print("error") 24 | break 25 | else: 26 | if reverse_flag: arr.pop() 27 | else: arr.popleft() 28 | 29 | if not zero_len_flag: 30 | if reverse_flag: 31 | arr.reverse() 32 | print("[" + ",".join(arr) + "]") 33 | else: 34 | print("[" + ",".join(arr) + "]") 35 | 36 | -------------------------------------------------------------------------------- /정승호/DFS와BFS/solution.py: -------------------------------------------------------------------------------- 1 | N,M,V=map(int,input().split()) 2 | matrix=[[0]*(N+1) for i in range(N+1)] 3 | for i in range(M): 4 | a,b = map(int,input().split()) 5 | matrix[a][b]=matrix[b][a]=1 6 | visit_list=[0]*(N+1) 7 | 8 | def dfs(V): 9 | visit_list[V] = 1 #방문한 점 1로 표시 10 | print(V, end=' ') 11 | for i in range(1,N+1): 12 | if(visit_list[i]==0 and matrix[V][i]==1): 13 | dfs(i) 14 | def bfs(V): 15 | queue=[V] #들려야 할 정점 저장 16 | visit_list[V]=0 #방문한 점 0으로 표시 17 | while queue: 18 | V=queue.pop(0) 19 | print(V, end=' ') 20 | for i in range(1, N+1): 21 | if(visit_list[i]==1 and matrix[V][i]==1): 22 | queue.append(i) 23 | visit_list[i]=0 24 | 25 | dfs(V) 26 | print() 27 | bfs(V) 28 | -------------------------------------------------------------------------------- /정승호/LRU_Cache/solution.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | class LRUCache: 4 | 5 | def __init__(self, capacity: int): 6 | self.cache = OrderedDict() 7 | self.capacity = capacity 8 | 9 | 10 | def get(self, key: int) -> int: 11 | if key not in self.cache: 12 | return -1 13 | else : 14 | self.cache.move_to_end(key) 15 | return self.cache[key] 16 | 17 | 18 | 19 | def put(self, key: int, value: int) -> None: 20 | self.cache[key] = value 21 | self.cache.move_to_end(key) 22 | if len(self.cache) > self.capacity : 23 | self.cache.popitem(last = False) 24 | 25 | 26 | 27 | # Your LRUCache object will be instantiated and called as such: 28 | # obj = LRUCache(capacity) 29 | # param_1 = obj.get(key) 30 | # obj.put(key,value) 31 | -------------------------------------------------------------------------------- /정승호/N으로_표현/solution.py: -------------------------------------------------------------------------------- 1 | def solution(N, number): 2 | answer = 0 3 | if N == number: 4 | return 1 5 | 6 | DP = [set() for _ in range(8)] 7 | for index, num in enumerate(DP): 8 | num.add(int(str(N)*(index+1))) 9 | 10 | for i in range(1,8): 11 | for j in range(i): 12 | for val1 in DP[j]: 13 | for val2 in DP[i-j-1]: 14 | DP[i].add(val1+val2) 15 | DP[i].add(val1-val2) 16 | DP[i].add(val1*val2) 17 | if val2 != 0: 18 | DP[i].add(val1//val2) 19 | if number in DP[i]: 20 | answer = i+1 21 | break 22 | else : 23 | answer = -1 24 | 25 | return answer 26 | -------------------------------------------------------------------------------- /정승호/Remove-Duplicates-from-Sorted-List-II/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: ListNode) -> ListNode: 8 | curr = head 9 | temp=pre = ListNode(0,None) 10 | temp.next = curr 11 | 12 | while curr and curr.next : 13 | if curr.val == curr.next.val: 14 | while (curr and curr.next and curr.val == curr.next.val): 15 | curr = curr.next 16 | 17 | curr = curr.next 18 | pre.next = curr 19 | else : 20 | pre = pre.next 21 | curr = curr.next 22 | 23 | return temp.next 24 | -------------------------------------------------------------------------------- /정승호/SQL/Revising_the_Select_Query_II/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME 2 | FROM CITY 3 | WHERE POPULATION > 120000 and COUNTRYCODE = 'USA' 4 | -------------------------------------------------------------------------------- /정승호/SQL/japanese-cities-attributesselect-by-id/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY WHERE COUNTRYCODE = 'JPN'; 2 | -------------------------------------------------------------------------------- /정승호/SQL/japanese-cities-name/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM CITY WHERE COUNTRYCODE = 'JPN'; 2 | 3 | -------------------------------------------------------------------------------- /정승호/SQL/more-than-75-marks/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME 2 | FROM STUDENTS 3 | WHERE MARKS > 75 4 | ORDER BY RIGHT(NAME, 3), ID; 5 | -------------------------------------------------------------------------------- /정승호/SQL/name-of-employees/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT name FROM Employee 2 | ORDER BY NAME; 3 | -------------------------------------------------------------------------------- /정승호/SQL/salary-of-employees/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM Employee 2 | WHERE (salary>2000 and months < 10) 3 | ORDER BY employee_id ASC; 4 | -------------------------------------------------------------------------------- /정승호/SQL/select-all/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY 2 | -------------------------------------------------------------------------------- /정승호/SQL/select-by-id/solution.sql: -------------------------------------------------------------------------------- 1 | select * from City where ID=1661; 2 | 3 | 4 | -------------------------------------------------------------------------------- /정승호/SQL/the-pads/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT CONCAT(NAME,'(',SUBSTR(OCCUPATION,1,1),')') AS N 2 | FROM OCCUPATIONS 3 | ORDER BY N; 4 | SELECT CONCAT('There are a total of ',COUNT(OCCUPATION),' ',LOWER(OCCUPATION),'s.') 5 | FROM OCCUPATIONS 6 | GROUP BY OCCUPATION 7 | ORDER BY COUNT(OCCUPATION), OCCUPATION; 8 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-1/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT CITY, STATE FROM STATION; 2 | 3 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-10/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '[^aeiou]$'; 4 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-11/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '^[^aeiou]|[^aeiou]$'; 4 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-12/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '^[^aeiou]' AND CITY REGEXP '[^aeiou]$'; 4 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-3/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT distinct CITY 2 | FROM STATION 3 | WHERE (ID % 2) = 0; 4 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-4/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT COUNT(CITY) - COUNT(DISTINCT CITY) 2 | FROM STATION; 3 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-5/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT CITY, CHAR_LENGTH(CITY) 2 | FROM STATION 3 | ORDER BY 2 ASC,1 LIMIT 1; 4 | 5 | SELECT CITY, CHAR_LENGTH(CITY) 6 | FROM STATION 7 | ORDER BY 2 DESC,1 DESC LIMIT 1; 8 | 9 | 10 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-6/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '^[aeiou]'; 4 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-7/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '[aeiou]$'; 4 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-8/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT City FROM Station 2 | WHERE City REGEXP '^[aeiou]' and City REGEXP '[aeiou]$'; 3 | -------------------------------------------------------------------------------- /정승호/SQL/weather-observation-station-9/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY 2 | FROM STATION 3 | WHERE CITY REGEXP '^[^aeiou]'; 4 | -------------------------------------------------------------------------------- /정승호/SQL/what-type-of-triangle/solution.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | CASE 3 | WHEN A = B AND B = C THEN 'Equilateral' 4 | WHEN A >= B+C OR B >= A+C OR C >= A+B THEN 'Not A Triangle' 5 | WHEN A = B OR A = C OR B = C THEN 'Isosceles' 6 | ELSE 'Scalene' END 7 | FROM TRIANGLES; 8 | 9 | -------------------------------------------------------------------------------- /정승호/Sherlock_and_the_Valid_String/solution.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import random 4 | import re 5 | import sys 6 | 7 | # Complete the isValid function below. 8 | def isValid(s): 9 | freq = {} 10 | cnt = set() 11 | for ch in s: 12 | if ch in freq: 13 | freq[ch] += 1 14 | else : 15 | freq[ch] = 1 16 | 17 | for num in freq.values(): 18 | cnt.add(num) 19 | 20 | if len(cnt) == 1: 21 | return 'YES' 22 | 23 | elif len(cnt) > 2: 24 | return 'NO' 25 | 26 | else: 27 | for key in freq: 28 | freq[key] -= 1 29 | temp = list(freq.values()) 30 | try: 31 | temp.remove(0) 32 | except: 33 | pass 34 | if len(set(temp)) == 1: 35 | return 'YES' 36 | else : 37 | freq[key]+=1 38 | return 'NO' 39 | 40 | if __name__ == '__main__': 41 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 42 | 43 | s = input() 44 | 45 | result = isValid(s) 46 | 47 | fptr.write(result + '\n') 48 | 49 | fptr.close() 50 | -------------------------------------------------------------------------------- /정승호/Swap-Node-in-Pairs/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | volume = 0 4 | 5 | if not height: 6 | return 0 7 | 8 | left, right = 0, len(height)-1 9 | left_max, right_max = height[left], height[right] 10 | 11 | while left < right: 12 | left_max, right_max = max(left_max, height[left]), max(right_max, height[right]) 13 | 14 | if left_max <= right_max: 15 | volume += left_max - height[left] 16 | left+=1 17 | else : 18 | volume += right_max - height[right] 19 | right -=1 20 | 21 | return volume 22 | -------------------------------------------------------------------------------- /정승호/Two-Sum/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | 4 | for i in range(len(nums)): 5 | for j in range(i+1, len(nums)): 6 | if nums[i] + nums[j] == target: 7 | return [i,j] 8 | -------------------------------------------------------------------------------- /정승호/Z/solution.py: -------------------------------------------------------------------------------- 1 | n, r, c = map(int, input().split()) 2 | answer = 0 3 | 4 | while n >= 1: 5 | temp = 2 ** (n - 1) 6 | if n == 1: 7 | if r is 0 and c is 1: 8 | answer += 1 9 | elif r is 1 and c is 0: 10 | answer += 2 11 | elif r is 1 and c is 1: 12 | answer += 3 13 | break 14 | 15 | if r < temp <= c: # 2사분면 16 | answer += temp ** 2 17 | c -= temp 18 | elif c < temp <= r: # 3사분면 19 | answer += (temp ** 2) * 2 20 | r -= temp 21 | elif temp <= c and temp <= r: # 4 사분면 22 | answer += (temp ** 2) * 3 23 | r -= temp 24 | c -= temp 25 | 26 | n -= 1 27 | 28 | print(answer) 29 | -------------------------------------------------------------------------------- /정승호/alphabet-board-path/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def alphabetBoardPath(self, target: str) -> str: 3 | board = ["abcde", "fghij", "klmno", "pqrst", 4 | "uvwxy", "z"] 5 | position = {} 6 | for r in range(6): 7 | for c in range(len(board[r])): 8 | position[board[r][c]] = (r,c) 9 | 10 | answer = '' 11 | 12 | x,y = 0,0 13 | 14 | for ch in target: 15 | dx, dy = position[ch] 16 | ups = max(0, x - dx) 17 | rights = max(0, dy - y) 18 | lefts = max(0, y - dy) 19 | downs = max(0, dx - x) 20 | answer += 'U' * ups + 'L' * lefts + 'R' * rights + 'D' * downs + '!' 21 | x, y = dx, dy 22 | 23 | return answer 24 | -------------------------------------------------------------------------------- /정승호/balanced-binary-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isBalanced(self, root: TreeNode) -> bool: 9 | def check(root): 10 | if not root: 11 | return 0 12 | 13 | left = check(root.left) 14 | right = check(root.right) 15 | # 높이 차이가 나는 경우 -1, 이외에는 높이에 따라 1 증가 16 | if left == -1 or \ 17 | right == -1 or \ 18 | abs(left - right) > 1: 19 | return -1 20 | return max(left, right) + 1 21 | 22 | return check(root) != -1 23 | -------------------------------------------------------------------------------- /정승호/best-time-to-buy-and-sell-stock-ii/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | profit = 0 4 | for i in range(len(prices)-1): 5 | if prices[i] < prices[i+1]: 6 | profit += (prices[i+1] - prices[i]) 7 | return profit 8 | -------------------------------------------------------------------------------- /정승호/best-time-to-buy-and-sell-stock/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | profit = 0 4 | min_price = 999999999999999 5 | for price in prices: 6 | min_price = min(price, min_price) 7 | profit = max(profit, price - min_price) 8 | return profit 9 | -------------------------------------------------------------------------------- /정승호/binary-search-tree-to-greater-sum-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | val: int = 0 9 | def bstToGst(self, root: TreeNode) -> TreeNode: 10 | # 중위 순회 노드 값 누적 11 | if root : 12 | self.bstToGst(root.right) 13 | self.val += root.val 14 | root.val = self.val 15 | self.bstToGst(root.left) 16 | return root 17 | -------------------------------------------------------------------------------- /정승호/binary-search/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | left, right = 0, len(nums)-1 4 | while left <= right: 5 | pivot = left + (right-left)//2 6 | if nums[pivot] == target: 7 | return pivot 8 | if target < nums[pivot]: 9 | right = pivot - 1 10 | else: 11 | left = pivot + 1 12 | return -1 13 | 14 | -------------------------------------------------------------------------------- /정승호/cheapest-flights-within-k-stops/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: 3 | graph = collections.defaultdict(list) 4 | # 그래프의 인접 리스트 구셩 5 | for u,v,w in flights: 6 | graph[u].append((v,w)) 7 | 8 | # 큐 변수 : [(가격, 정점, 남은 가능 경유지 수)] 9 | Q = [(0, src, K)] 10 | 11 | # 우선순위 큐 최솟값 기준으로 도착점까지 최소 비용 판별 12 | while Q: 13 | price, node, k = heapq.heappop(Q) 14 | if node == dst: 15 | return price 16 | if k >= 0: 17 | for v,w in graph[node]: 18 | alt = price + w 19 | heapq.heappush(Q,(alt,v,k-1)) 20 | return -1 21 | 22 | -------------------------------------------------------------------------------- /정승호/combination-sum/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | result = [] 4 | def dfs(csum, index, path): 5 | if csum < 0: 6 | return 7 | if csum == 0: 8 | result.append(path) 9 | return 10 | 11 | for i in range(index,len(candidates)): 12 | dfs(csum - candidates[i], i, path + [candidates[i]] ) 13 | 14 | dfs(target, 0, []) 15 | return result 16 | 17 | -------------------------------------------------------------------------------- /정승호/combinations/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | result = [] 4 | 5 | def dfs(elements, start, k): 6 | if k == 0: 7 | result.append(elements[:]) 8 | for i in range(start, n+1): 9 | elements.append(i) 10 | dfs(elements, i+1, k-1) 11 | elements.pop() 12 | 13 | dfs([],1,k) 14 | return result 15 | 16 | -------------------------------------------------------------------------------- /정승호/contains-duplicate/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | nums.sort() 4 | for i in range(1, len(nums)): 5 | if nums[i-1] == nums[i]: 6 | return True 7 | return False 8 | 9 | 10 | -------------------------------------------------------------------------------- /정승호/convert-sorted-array-to-binary-search-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 9 | if not nums: 10 | return None 11 | 12 | mid = len(nums) // 2 13 | 14 | # 분할 정복으로 이진 검색 결과 트리 구성 15 | node = TreeNode(nums[mid]) 16 | node.left = self.sortedArrayToBST(nums[:mid]) 17 | node.right = self.sortedArrayToBST(nums[mid + 1:]) 18 | 19 | return node 20 | -------------------------------------------------------------------------------- /정승호/daily-temperatures/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, T: List[int]) -> List[int]: 3 | answer = [0]*len(T) 4 | stack = [] 5 | for i, cur in enumerate(T): 6 | while stack and cur > T[stack[-1]]: 7 | last = stack.pop() 8 | answer[last] = i - last 9 | stack.append(i) 10 | return answer 11 | -------------------------------------------------------------------------------- /정승호/design-circular-queue/solution.py: -------------------------------------------------------------------------------- 1 | class MyCircularQueue: 2 | 3 | def __init__(self, k: int): 4 | """ 5 | Initialize your data structure here. Set the size of the queue to be k. 6 | """ 7 | self.len = 0 # 큐 내부의 자료의 갯수를 구함 8 | self.max_size = k 9 | self.queue = [None for _ in range(k)] 10 | self.front = self.rear = -1 11 | 12 | 13 | 14 | def enQueue(self, value: int) -> bool: 15 | """ 16 | Insert an element into the circular queue. Return true if the operation is successful. 17 | """ 18 | 19 | # Queue is full 20 | if self.len == self.max_size: 21 | return False 22 | 23 | # Queue is Empty 24 | elif self.rear == -1 : 25 | self.front = 0 26 | self.rear = 0 27 | self.queue[self.rear] = value 28 | self.len += 1 29 | return True 30 | 31 | else : 32 | # Next position of rear 33 | self.rear = (self.rear + 1) % self.max_size 34 | self.queue[self.rear] = value 35 | self.len += 1 36 | return True 37 | 38 | 39 | 40 | 41 | def deQueue(self) -> bool: 42 | """ 43 | Delete an element from the circular queue. Return true if the operation is successful. 44 | """ 45 | 46 | # Queue is empty 47 | if self.len == 0: 48 | return False 49 | 50 | # Only one component 51 | elif self.front == self.rear: 52 | self.front = -1 53 | self.rear = -1 54 | 55 | 56 | else : 57 | self.front = (self.front+1) % self.max_size 58 | self.len -= 1 59 | return True 60 | 61 | 62 | 63 | 64 | 65 | def Front(self) -> int: 66 | """ 67 | Get the front item from the queue. 68 | """ 69 | if self.len == 0: 70 | return -1 71 | else : 72 | return self.queue[self.front] 73 | 74 | 75 | 76 | 77 | 78 | def Rear(self) -> int: 79 | """ 80 | Get the last item from the queue. 81 | """ 82 | if self.len == 0: 83 | return -1 84 | else : 85 | return self.queue[self.rear] 86 | 87 | 88 | def isEmpty(self) -> bool: 89 | """ 90 | Checks whether the circular queue is empty or not. 91 | """ 92 | return self.len == 0 93 | 94 | 95 | def isFull(self) -> bool: 96 | """ 97 | Checks whether the circular queue is full or not. 98 | """ 99 | return self.len == self.max_size 100 | 101 | 102 | 103 | # Your MyCircularQueue object will be instantiated and called as such: 104 | # obj = MyCircularQueue(k) 105 | # param_1 = obj.enQueue(value) 106 | # param_2 = obj.deQueue() 107 | # param_3 = obj.Front() 108 | # param_4 = obj.Rear() 109 | # param_5 = obj.isEmpty() 110 | # param_6 = obj.isFull() 111 | -------------------------------------------------------------------------------- /정승호/design-hashmap/solution.py: -------------------------------------------------------------------------------- 1 | # open addressing 방식의 hashmap 구현 2 | 3 | class ListNode: 4 | 5 | def __init__(self, key = None, value = None): 6 | self.key = key 7 | self.value = value 8 | self.next = None 9 | 10 | 11 | class MyHashMap: 12 | 13 | def __init__(self): 14 | """ 15 | Initialize your data structure here. 16 | """ 17 | self.size = 1000 18 | self.table = collections.defaultdict(ListNode) 19 | # 존재하지 않는 키를 조회할 경우 자동으로 ListNode 생성 20 | 21 | 22 | 23 | 24 | def put(self, key: int, value: int) -> None: 25 | """ 26 | value will always be non-negative. 27 | """ 28 | index = key % self.size 29 | # 인덱스에 노드가 없으면 삽입 후 종료 30 | if self.table[index].value == None: 31 | self.table[index] = ListNode(key, value) 32 | return 33 | 34 | # 인덱스에 노드가 존재하는 경우 연결리스트 처리 35 | p = self.table[index] 36 | while p: 37 | if p.key == key: 38 | p.value = value 39 | return 40 | if p.next is None: 41 | break 42 | p = p.next 43 | p.next = ListNode(key, value) 44 | 45 | 46 | 47 | def get(self, key: int) -> int: 48 | """ 49 | Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key 50 | """ 51 | index = key % self.size 52 | if self.table[index].value is None: 53 | return -1 54 | 55 | # 노드가 존재할 때 일치하는 키 탐색 56 | p = self.table[index] 57 | while p: 58 | if p.key == key: 59 | return p.value 60 | p = p.next 61 | return -1 62 | 63 | 64 | def remove(self, key: int) -> None: 65 | """ 66 | Removes the mapping of the specified value key if this map contains a mapping for the key 67 | """ 68 | index = key % self.size 69 | if self.table[index].value is None: 70 | return 71 | 72 | # 인덱스의 첫번째 노드일때 삭제 73 | p = self.table[index] 74 | if p.key == key: 75 | self.table[index] = ListNode() if p.next is None else p.next 76 | return 77 | 78 | 79 | # 연결리스트 노드 삭제 80 | prev = p 81 | while p: 82 | if p.key == key: 83 | prev.next = p.next 84 | return 85 | prev, p = p, prev 86 | 87 | 88 | 89 | 90 | 91 | 92 | # Your MyHashMap object will be instantiated and called as such: 93 | # obj = MyHashMap() 94 | # obj.put(key,value) 95 | # param_2 = obj.get(key) 96 | # obj.remove(key) 97 | -------------------------------------------------------------------------------- /정승호/diameter-of-binary-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 9 | self.ans = 0 10 | 11 | def dfs(root): 12 | if not root: 13 | return 0 14 | left = dfs(root.left) 15 | right = dfs(root.right) 16 | self.ans = max(self.ans, left + right) 17 | return max(left, right) +1 18 | dfs(root) 19 | return self.ans 20 | -------------------------------------------------------------------------------- /정승호/different-ways-to-add-parentheses/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diffWaysToCompute(self, expression: str) -> List[int]: 3 | def calc(expression): 4 | result = [] 5 | for i,c in enumerate(expression): 6 | if c in '+-*': 7 | left = calc(expression[:i]) 8 | right = calc(expression[i+1:]) 9 | 10 | for a in left: 11 | for b in right: 12 | if c == '+': 13 | result.append(a+b) 14 | elif c == '-': 15 | result.append(a-b) 16 | else: 17 | result.append(a*b) 18 | if not result: 19 | return [int(expression)] 20 | 21 | return result 22 | 23 | return calc(expression) 24 | 25 | -------------------------------------------------------------------------------- /정승호/find-n-unique-integers-sum-up-to-zero/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumZero(self, n: int) -> List[int]: 3 | num, rem = n//2, n%2 4 | answer = [] 5 | if rem != 0: answer.append(0) 6 | for i in range(1, num+1): 7 | answer.append(-i) 8 | answer.append(i) 9 | return answer 10 | 11 | -------------------------------------------------------------------------------- /정승호/first-bad-version/solution.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return an integer 4 | # def isBadVersion(version): 5 | 6 | class Solution: 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | left = 1 13 | right = n 14 | while (left < right) : 15 | mid = left + (right-left) //2 16 | if isBadVersion(mid): 17 | right = mid 18 | else: 19 | left = mid+1 20 | 21 | return left 22 | -------------------------------------------------------------------------------- /정승호/flood-fill/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: 3 | R,C= len(image), len(image[0]) 4 | color = image[sr][sc] 5 | if color == newColor: return image 6 | def dfs(r, c): 7 | if image[r][c] == color: 8 | image[r][c] = newColor 9 | if r >= 1: dfs(r-1,c) 10 | if r+1 < R: dfs(r+1,c) 11 | if c >= 1: dfs(r,c-1) 12 | if c+1 < C: dfs(r,c+1) 13 | dfs(sr,sc) 14 | return image 15 | 16 | -------------------------------------------------------------------------------- /정승호/gas-station/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | if sum(gas) < sum(cost): 4 | return -1 5 | n, start, agg = len(gas), 0, 0 6 | for i in range(n): 7 | agg += (gas[i]- cost[i]) 8 | if agg < 0: 9 | start, agg = i+1, 0 10 | return start 11 | 12 | -------------------------------------------------------------------------------- /정승호/group-anagrams/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | answer = collections.defaultdict(list) 4 | for ana in strs: 5 | answer[''.join(sorted(ana))].append(ana) 6 | return answer.values() 7 | -------------------------------------------------------------------------------- /정승호/implement-queue-using-stacks/solution.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.input = [] 8 | self.output = [] 9 | 10 | 11 | def push(self, x: int) -> None: 12 | """ 13 | Push element x to the back of queue. 14 | """ 15 | self.input.append(x) 16 | 17 | 18 | def pop(self) -> int: 19 | """ 20 | Removes the element from in front of queue and returns that element. 21 | """ 22 | self.peek() 23 | return self.output.pop() 24 | 25 | 26 | 27 | 28 | def peek(self) -> int: 29 | """ 30 | Get the front element. 31 | """ 32 | # output에 값이 없을 시 input에 있는 값들 모두 output으로 이동 33 | if not self.output: 34 | while self.input: 35 | self.output.append(self.input.pop()) 36 | return self.output[-1] 37 | 38 | 39 | def empty(self) -> bool: 40 | """ 41 | Returns whether the queue is empty. 42 | """ 43 | return self.input == [] and self.output == [] 44 | 45 | 46 | 47 | # Your MyQueue object will be instantiated and called as such: 48 | # obj = MyQueue() 49 | # obj.push(x) 50 | # param_2 = obj.pop() 51 | # param_3 = obj.peek() 52 | # param_4 = obj.empty() 53 | -------------------------------------------------------------------------------- /정승호/implement-stack-using-queues/solution.py: -------------------------------------------------------------------------------- 1 | class MyStack: 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.q = collections.deque() 8 | 9 | 10 | def push(self, x: int) -> None: 11 | """ 12 | Push element x onto stack. 13 | """ 14 | self.q.append(x) 15 | # 요소 삽입 후 맨 앞으로 오게 재정렬 16 | for _ in range(len(self.q)-1): 17 | self.q.append(self.q.popleft()) 18 | 19 | 20 | def pop(self) -> int: 21 | """ 22 | Removes the element on top of the stack and returns that element. 23 | """ 24 | return self.q.popleft() 25 | 26 | 27 | def top(self) -> int: 28 | """ 29 | Get the top element. 30 | """ 31 | return self.q[0] 32 | 33 | 34 | def empty(self) -> bool: 35 | """ 36 | Returns whether the stack is empty. 37 | """ 38 | return len(self.q)==0 39 | 40 | 41 | 42 | # Your MyStack object will be instantiated and called as such: 43 | # obj = MyStack() 44 | # obj.push(x) 45 | # param_2 = obj.pop() 46 | # param_3 = obj.top() 47 | # param_4 = obj.empty() 48 | -------------------------------------------------------------------------------- /정승호/invert-binary-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def invertTree(self, root: TreeNode) -> TreeNode: 9 | queue = collections.deque([root]) 10 | while queue: 11 | node = queue.popleft() 12 | if node: 13 | node.left, node.right = node.right, node.left 14 | queue.append(node.left) 15 | queue.append(node.right) 16 | 17 | return root 18 | -------------------------------------------------------------------------------- /정승호/is-graph-bipartite/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isBipartite(self, graph: List[List[int]]) -> bool: 3 | colors = {} 4 | 5 | def dfs(graph, node, colors, color): 6 | colors[node] = color 7 | for node_to in graph[node]: 8 | if node_to in colors: 9 | if colors[node_to] == colors[node]: 10 | return False 11 | else : 12 | if not dfs(graph, node_to, colors, color*-1): 13 | return False 14 | return True 15 | 16 | for node_from in range(len(graph)): 17 | if node_from not in colors and not dfs(graph, node_from, colors, 1): 18 | return False 19 | return True 20 | -------------------------------------------------------------------------------- /정승호/jump-game-iii/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canReach(self, arr: List[int], start: int) -> bool: 3 | memo = {} 4 | def dfs(arr,i,memo): 5 | if i < 0 or i>= len(arr): 6 | return False 7 | if arr[i]==0: 8 | return True 9 | if i in memo: 10 | return memo[i] 11 | memo[i]=False 12 | if dfs(arr, i-arr[i], memo): 13 | return True 14 | if dfs(arr,i+arr[i], memo): 15 | return True 16 | return False 17 | return dfs(arr, start, memo) 18 | -------------------------------------------------------------------------------- /정승호/jump-game/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | current_index = len(nums)-1 4 | for i in range(len(nums)-1,-1,-1): 5 | if nums[i] + i >= current_index: 6 | current_index = i 7 | return current_index == 0 8 | -------------------------------------------------------------------------------- /정승호/k-th-symbol-in-grammar/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthGrammar(self, N: int, K: int) -> int: 3 | if N == 1: 4 | return 0 5 | 6 | if(K%2 == 1): 7 | return self.kthGrammar(N-1, (K//2)+1) 8 | 9 | if self.kthGrammar(N-1, K//2) == 0: 10 | return 1 11 | 12 | if self.kthGrammar(N-1, K//2) == 1: 13 | return 0 14 | -------------------------------------------------------------------------------- /정승호/keys-and-rooms/solution.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 4 | visited = set() 5 | 6 | def dfs(room, visited) : 7 | if room not in visited: 8 | visited.add(room) 9 | for key in rooms[room]: 10 | dfs(key,visited) 11 | dfs(0,visited) 12 | return len(visited) == len(rooms) 13 | -------------------------------------------------------------------------------- /정승호/letter-combinations-of-a-phone-number/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | dic = {"2" : "abc", "3":"def", "4" : "ghi", "5":"jkl", 4 | "6":"mno", "7" : "pqrs", "8" : "tuv", "9" : "wxyz"} 5 | result = [] 6 | path = "" 7 | def dfs(index, path): 8 | if len(path) == len(digits): 9 | result.append(path) 10 | return 11 | for i in range(index, len(digits)): 12 | for j in dic[digits[i]]: 13 | dfs(i+1, path + j) 14 | 15 | if not digits: 16 | return [] 17 | 18 | dfs(0,"") 19 | return result 20 | -------------------------------------------------------------------------------- /정승호/longest-palindromic-substring/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> str: 3 | answer = "" 4 | def check(l,r): 5 | while l >=0 and r < len(s) and s[l] == s[r]: 6 | l -=1 7 | r +=1 8 | return s[l+1:r] 9 | 10 | for i in range(len(s)): 11 | temp = check(i,i) 12 | if len(temp) > len(answer): 13 | answer = temp 14 | 15 | temp = check(i,i+1) 16 | if len(temp) > len(answer): 17 | answer = temp 18 | return answer 19 | 20 | 21 | -------------------------------------------------------------------------------- /정승호/longest-substring-without-repeating-characters/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | used = {} 4 | max_length= start = 0 5 | 6 | for index, char in enumerate(s): 7 | if char in used and start <= used[char]: 8 | start = used[char] + 1 9 | else : 10 | max_length = max(max_length, index - start + 1) 11 | used[char] = index 12 | 13 | return max_length 14 | -------------------------------------------------------------------------------- /정승호/longest-univalue-path/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | result = 0 9 | def longestUnivaluePath(self, root: TreeNode) -> int: 10 | 11 | def dfs(node: TreeNode): 12 | 13 | if node is None: 14 | return 0 15 | 16 | left = dfs(node.left) 17 | right = dfs(node.right) 18 | 19 | if node.left and node.left.val == node.val: 20 | left += 1 21 | else: 22 | left = 0 23 | 24 | if node.right and node.right.val == node.val: 25 | right += 1 26 | else: 27 | right = 0 28 | 29 | self.result = max(self.result, left + right) 30 | 31 | return max(left, right) 32 | 33 | dfs(root) 34 | return self.result 35 | -------------------------------------------------------------------------------- /정승호/max-area-of-island/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 3 | answer = 0 4 | def dfs(i,j): 5 | counter = 0 6 | if i < 0 or i >= len(grid) or \ 7 | j < 0 or j >= len(grid[0]) or \ 8 | grid[i][j] != 1: 9 | return 0 10 | else: 11 | counter += 1 12 | grid[i][j] = 0 13 | counter += dfs(i+1,j) 14 | counter += dfs(i-1,j) 15 | counter += dfs(i,j+1) 16 | counter += dfs(i, j-1) 17 | 18 | return counter 19 | 20 | for i in range(len(grid)): 21 | for j in range(len(grid[0])): 22 | if grid[i][j] == 1: 23 | counter = dfs(i,j) 24 | answer = max(answer, counter) 25 | 26 | return answer 27 | 28 | -------------------------------------------------------------------------------- /정승호/maximum-depth-of-binary-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxDepth(self, root: TreeNode) -> int: 9 | if root is None: 10 | return 0 11 | queue = collections.deque([root]) 12 | depth = 0 13 | while queue: 14 | depth += 1 15 | for _ in range(len(queue)): 16 | cur_root = queue.popleft() 17 | if cur_root.left: 18 | queue.append(cur_root.left) 19 | if cur_root.right: 20 | queue.append(cur_root.right) 21 | return depth 22 | -------------------------------------------------------------------------------- /정승호/merge-two-binary-trees/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 9 | if t1 and t2: 10 | node = TreeNode(t1.val + t2.val) 11 | node.left = self.mergeTrees(t1.left, t2.left) 12 | node.right = self.mergeTrees(t1.right, t2.right) 13 | return node 14 | else : 15 | return t1 or t2 16 | -------------------------------------------------------------------------------- /정승호/middle-of-the-linked-list/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | slow = fast = head 9 | while fast and fast.next: 10 | slow = slow.next 11 | fast = fast.next.next 12 | return slow 13 | 14 | -------------------------------------------------------------------------------- /정승호/minimum-deletions-to-make-character-frequencies-unique/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDeletions(self, s: str) -> int: 3 | freq = {} 4 | for ch in s: 5 | freq[ch] = 1 + freq.get(ch,0) 6 | 7 | result = 0 8 | appears = set() 9 | for k in freq.values(): 10 | while k in appears: 11 | k-=1 12 | result+=1 13 | if k: 14 | appears.add(k) 15 | return result 16 | -------------------------------------------------------------------------------- /정승호/minimum-distance-between-bst-nodes/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | prev = -sys.maxsize 9 | result = sys.maxsize 10 | 11 | # 재귀 구조 중위 순회 비교 결과 12 | def minDiffInBST(self, root: TreeNode) -> int: 13 | if root.left: 14 | self.minDiffInBST(root.left) 15 | 16 | self.result = min(self.result, root.val - self.prev) 17 | self.prev = root.val 18 | 19 | if root.right: 20 | self.minDiffInBST(root.right) 21 | 22 | return self.result 23 | -------------------------------------------------------------------------------- /정승호/minimum-height-trees/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 3 | if n <= 1: 4 | return [0] 5 | 6 | # 양방향 그래프 구성 7 | graph = collections.defaultdict(list) 8 | for i,j in edges: 9 | graph[i].append(j) 10 | graph[j].append(i) 11 | 12 | # 첫번째 리프 노드 추가 13 | leaves = [] 14 | for i in range(n+1): 15 | if len(graph[i]) == 1: 16 | leaves.append(i) 17 | 18 | # 루트 노드만 남을 때까지 반복 제거 19 | while n > 2: 20 | n -= len(leaves) 21 | new_leaves = [] 22 | for leaf in leaves: 23 | neighbor = graph[leaf].pop() 24 | graph[neighbor].remove(leaf) 25 | 26 | if len(graph[neighbor]) == 1: 27 | new_leaves.append(neighbor) 28 | 29 | leaves = new_leaves 30 | 31 | 32 | return leaves 33 | -------------------------------------------------------------------------------- /정승호/move-zeroes/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums: List[int]) -> None: 3 | 4 | i, j = 0, 0 5 | 6 | for index in range(len(nums)): 7 | if nums[index] == 0: 8 | j += 1 9 | else: 10 | nums[index], nums[i] = nums[i], nums[index] 11 | i += 1 12 | 13 | 14 | -------------------------------------------------------------------------------- /정승호/network-delay-time/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: 3 | graph = collections.defaultdict(list) 4 | # 그래프 인접 리스트 구성 5 | for u,v,w in times: 6 | graph[u].append((v,w)) 7 | 8 | # 큐 변수 : [(소요시간, 정점)] 9 | Q = [(0,K)] 10 | dist = collections.defaultdict(int) 11 | 12 | # 우선순위 큐 최솟값 기주으로 정점까지 최단 경로 삽입 13 | while Q: 14 | time, node = heapq.heappop(Q) 15 | if node not in dist: 16 | dist[node] = time 17 | for v,w in graph[node]: 18 | alt = time + w 19 | heapq.heappush(Q,(alt,v)) 20 | 21 | # 모든 노드의 최단 경로 존재 여부 판별 22 | if len(dist) == N: 23 | return max(dist.values()) 24 | return -1 25 | -------------------------------------------------------------------------------- /정승호/number-of-islands/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIslands(self, grid: List[List[str]]) -> int: 3 | 4 | def dfs(i,j): 5 | if i < 0 or i >= len(grid) or \ 6 | j < 0 or j >= len(grid[0]) or \ 7 | grid[i][j] != '1': 8 | return 9 | 10 | grid[i][j] = 0 11 | dfs(i+1,j) 12 | dfs(i-1,j) 13 | dfs(i,j+1) 14 | dfs(i,j-1) 15 | 16 | count = 0 17 | for i in range(len(grid)): 18 | for j in range(len(grid[0])): 19 | if grid[i][j] == '1': 20 | dfs(i,j) 21 | count +=1 22 | return answer 23 | -------------------------------------------------------------------------------- /정승호/partition-labels/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partitionLabels(self, S: str) -> List[int]: 3 | 4 | rightMost = {c:index for index, c in enumerate(S)} 5 | result = [] 6 | left , right = 0,0 7 | for i, letter in enumerate(S): 8 | right = max(right, rightMost[letter]) 9 | if i == right: 10 | result += [right - left + 1] 11 | left = i +1 12 | 13 | return result 14 | -------------------------------------------------------------------------------- /정승호/permutation-in-string/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkInclusion(self, s1: str, s2: str) -> bool: 3 | s1 = sorted(s1) 4 | for i in range(len(s2)-len(s1)+1): 5 | if s1 == sorted(s2[i:i+len(s1)]): 6 | return True 7 | return False 8 | -------------------------------------------------------------------------------- /정승호/permutations/solutions.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | result = [] 4 | 5 | def dfs(nums, path, result): 6 | if not nums: 7 | result.append(path) 8 | 9 | for i in range(len(nums)): 10 | dfs(nums[:i] + nums[i+1:], path+[nums[i]], result) 11 | 12 | dfs(nums, [], result) 13 | return result 14 | 15 | -------------------------------------------------------------------------------- /정승호/product-of-array-except-self/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | out = [] 4 | p = 1 5 | for i in range(0, len(nums)): 6 | out.append(p) 7 | p = p*nums[i] 8 | p = 1 9 | for i in range(len(nums)-1, 0 -1, -1): 10 | out[i] = out[i]*p 11 | p = p*nums[i] 12 | return out 13 | -------------------------------------------------------------------------------- /정승호/queue-reconstruction-by-height/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: 3 | result = [] 4 | for i in sorted(people, key = lambda x : (-x[0], x[1])): 5 | result.insert(i[1], i) 6 | return result 7 | 8 | -------------------------------------------------------------------------------- /정승호/range-sum-of-bst/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: 9 | def dfs(node: TreeNode): 10 | if not node: 11 | return 0 12 | 13 | if node.val < low: 14 | return dfs(node.right) 15 | elif node.val > high: 16 | return dfs(node.left) 17 | return node.val + dfs(node.left) + dfs(node.right) 18 | 19 | return dfs(root) 20 | -------------------------------------------------------------------------------- /정승호/reconstruct-itinerary/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findItinerary(self, tickets: List[List[str]]) -> List[str]: 3 | graph = collections.defaultdict(list) 4 | for a,b in tickets: 5 | graph[a].append(b) 6 | for a in graph: 7 | graph[a].sort() 8 | result = [] 9 | def dfs(a): 10 | while graph[a]: 11 | dfs(graph[a].pop(0)) 12 | result.append(a) 13 | 14 | dfs('JFK') 15 | return result[::-1] 16 | -------------------------------------------------------------------------------- /정승호/regular-expression-matching/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s: str, p: str) -> bool: 3 | s, p = ' '+ s, ' '+ p 4 | lenS, lenP = len(s), len(p) 5 | dp = [[0]*(lenP) for i in range(lenS)] 6 | dp[0][0] = 1 7 | 8 | for j in range(1, lenP): 9 | if p[j] == '*': 10 | dp[0][j] = dp[0][j-2] 11 | 12 | for i in range(1, lenS): 13 | for j in range(1, lenP): 14 | if p[j] in {s[i], '.'}: 15 | dp[i][j] = dp[i-1][j-1] 16 | elif p[j] == "*": 17 | dp[i][j] = dp[i][j-2] or int(dp[i-1][j] and p[j-1] in {s[i], '.'}) 18 | 19 | return bool(dp[-1][-1]) 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /정승호/remove-nth-node-from-end-of-list/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 8 | f = head 9 | s = head 10 | total = 0 11 | 12 | while s: 13 | total+=1 14 | s = s.next 15 | 16 | position = total - n + 1 17 | 18 | i = 1 19 | while i < position-1: 20 | f = f.next 21 | i+=1 22 | if position==1: 23 | f = f.next 24 | return f 25 | else: 26 | f.next = f.next.next 27 | return head 28 | -------------------------------------------------------------------------------- /정승호/reorder-data-in-log-files/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 3 | log_letter = [] 4 | log_digit = [] 5 | for log in logs: 6 | if log.split(" ")[1].isdigit(): 7 | log_digit.append(log) 8 | else : 9 | log_letter.append(log) 10 | log_letter.sort(key = lambda x : (x.split()[1:], x.split()[0])) 11 | 12 | answer = log_letter + log_digit 13 | 14 | return answer 15 | -------------------------------------------------------------------------------- /정승호/reverse-string/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | left = 0 7 | right = len(s) -1 8 | 9 | while left < right : 10 | s[left], s[right] = s[right], s[left] 11 | left +=1 12 | right -=1 13 | -------------------------------------------------------------------------------- /정승호/reverse-words-in-a-string-iii/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | temp = s.split(" ") 4 | result = "" 5 | 6 | for word in temp: 7 | word = word[::-1] 8 | result += word + " " 9 | return result[:-1] 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /정승호/rotate-list/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 8 | 9 | # LinledList is Empty 10 | if not head : 11 | return head 12 | 13 | temp = head 14 | length = 1 # store length of LinkedList 15 | while (temp.next != None): 16 | temp = temp.next 17 | length += 1 18 | 19 | 20 | # k is bigger than length of LinkedList 21 | if k > length: 22 | k = k % length 23 | 24 | # Change k to right rotation 25 | k = length - k 26 | 27 | # No rotation needed 28 | if k == 0 or k == length: 29 | return head 30 | 31 | current = head 32 | cnt = 1 33 | 34 | while (cnt < k) and current.next != None: 35 | current = current.next 36 | cnt +=1 37 | 38 | if current == None: 39 | return head 40 | 41 | kNode = current 42 | temp.next = head 43 | head = kNode.next 44 | kNode.next = None 45 | 46 | return head 47 | 48 | 49 | -------------------------------------------------------------------------------- /정승호/search-a-2d-matrix/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 3 | if len(matrix) == 0: 4 | return False 5 | row,col = 0, len(matrix[0])-1 6 | while row < len(matrix) and col >= 0: 7 | if matrix[row][col] == target : return True 8 | elif matrix[row][col] < target: row += 1 9 | elif matrix[row][col] > target: col -= 1 10 | return False 11 | -------------------------------------------------------------------------------- /정승호/search-insert-position/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | end = len(nums) - 1 4 | start = 0 5 | if start == end: 6 | return 0 if target <= nums[0] else 1 7 | while start <= end: 8 | mid = start + ((end - start) // 2) 9 | if nums[mid] == target: 10 | return mid 11 | elif target < nums[mid]: 12 | end = mid -1 13 | else: 14 | start = mid + 1 15 | return mid if target < nums[mid] else mid + 1 16 | 17 | -------------------------------------------------------------------------------- /정승호/serialize-and-deserialize-binary-tree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Codec: 9 | 10 | def serialize(self, root): 11 | """Encodes a tree to a single string. 12 | 13 | :type root: TreeNode 14 | :rtype: str 15 | """ 16 | queue = collections.deque([root]) 17 | result = ['#'] 18 | # 트리 BFS 직렬화 19 | while queue : 20 | node = queue.popleft() 21 | if node: 22 | queue.append(node.left) 23 | queue.append(node.right) 24 | 25 | result.append(str(node.val)) 26 | else: 27 | result.append('#') 28 | return ' '.join(result) 29 | 30 | 31 | def deserialize(self, data): 32 | """Decodes your encoded data to tree. 33 | 34 | :type data: str 35 | :rtype: TreeNode 36 | """ 37 | if data == '# #': 38 | return None 39 | 40 | nodes = data.split() 41 | 42 | root = TreeNode(int(nodes[1])) 43 | queue = collections.deque([root]) 44 | index = 2 45 | # 빠른 런너처럼 자식 노드 결과를 먼저 확인 후 삽입 46 | while queue: 47 | node = queue.popleft() 48 | if nodes[index] is not '#': 49 | node.left = TreeNode(int(nodes[index])) 50 | queue.append(node.left) 51 | index += 1 52 | 53 | if nodes[index] is not '#': 54 | node.right = TreeNode(int(nodes[index])) 55 | queue.append(node.right) 56 | index += 1 57 | return root 58 | 59 | 60 | # Your Codec object will be instantiated and called as such: 61 | # ser = Codec() 62 | # deser = Codec() 63 | # ans = deser.deserialize(ser.serialize(root)) 64 | -------------------------------------------------------------------------------- /정승호/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 3 | left = 0 4 | right = len(numbers) - 1 5 | 6 | while left <= right: 7 | if numbers[left] + numbers[right] == target: 8 | return [left+1, right+1] 9 | elif numbers[left] + numbers[right] < target: 10 | left += 1 11 | else : right -= 1 12 | 13 | -------------------------------------------------------------------------------- /정승호/squares-of-a-sorted-array]/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, nums: List[int]) -> List[int]: 3 | left = 0 4 | right = len(nums)-1 5 | answer = [] 6 | while left <= right: 7 | if nums[left] ** 2 <= nums[right] ** 2: 8 | answer.insert(0, nums[right] ** 2) 9 | right -= 1 10 | elif nums[left] ** 2 > nums[right] ** 2: 11 | answer.insert(0, nums[left] ** 2) 12 | left += 1 13 | 14 | return answer 15 | 16 | -------------------------------------------------------------------------------- /정승호/subsets/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | result = [] 4 | 5 | def dfs(index, path): 6 | result.append(path) 7 | for i in range(index, len(nums)): 8 | dfs(i+1, path + [nums[i]]) 9 | 10 | dfs(0,[]) 11 | return result 12 | 13 | -------------------------------------------------------------------------------- /정승호/top-k-frequent-elements/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | table = {} 4 | for i in nums: 5 | if i in table: 6 | table[i] += 1 7 | else : 8 | table[i] = 1 9 | 10 | return sorted(table, key=table.get, reverse=True)[:k] 11 | -------------------------------------------------------------------------------- /정승호/trapping-rain-water/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | volume = 0 4 | 5 | if not height: 6 | return 0 7 | 8 | left, right = 0, len(height)-1 9 | left_max, right_max = height[left], height[right] 10 | 11 | while left < right: 12 | left_max, right_max = max(left_max, height[left]), max(right_max, height[right]) 13 | 14 | if left_max <= right_max: 15 | volume += left_max - height[left] 16 | left+=1 17 | else : 18 | volume += right_max - height[right] 19 | right -=1 20 | 21 | return volume 22 | -------------------------------------------------------------------------------- /정승호/valid-palindrome/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | # deque 자료형을 이용해서 문제를 풀면 4 | # brute force보다 실행시간이 더 빠르다. 5 | strs = collections.deque() 6 | 7 | for char in s: 8 | if char.isalnum(): 9 | strs.append(char.lower()) 10 | 11 | while len(strs) > 1: 12 | if strs.popleft() != strs.pop(): 13 | return False 14 | 15 | return True 16 | -------------------------------------------------------------------------------- /정승호/word-search/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def exist(self, board: List[List[str]], word: str) -> bool: 3 | visited = {} 4 | 5 | def dfs(i,j,position): 6 | nonlocal visited 7 | 8 | if position == len(word): 9 | return True 10 | 11 | if i < 0 or i == len(board) or j < 0 or j == len(board[0]) \ 12 | or visited.get((i,j)) or word[position] != board[i][j]: 13 | return False 14 | 15 | visited[(i,j)] = True 16 | res = dfs(i+1,j,position+1) or dfs(i,j+1,position+1) \ 17 | or dfs(i-1,j,position+1) or dfs(i,j-1,position+1) 18 | visited[(i,j)] = False 19 | 20 | return res 21 | 22 | for i in range(len(board)): 23 | for j in range(len(board[0])): 24 | if dfs(i,j,0): 25 | return True 26 | return False 27 | 28 | 29 | -------------------------------------------------------------------------------- /정승호/x만큼_간격이_있는_n개의_숫자/solution.py: -------------------------------------------------------------------------------- 1 | def solution(x, n): 2 | answer = [i * x + x for i in range(n)] 3 | return answer 4 | -------------------------------------------------------------------------------- /정승호/가운데_글자_가져오기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | 3 | if len(s)%2 == 1: 4 | return s[len(s)//2] 5 | 6 | else : 7 | return s[(len(s)//2)-1:(len(s)//2)+1] 8 | -------------------------------------------------------------------------------- /정승호/같은_숫자는_싫어/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arr): 2 | answer = [] 3 | 4 | for i in arr: 5 | if len(answer) == 0 : 6 | answer.append(i) 7 | 8 | if len(answer) != 0 and answer[-1] != i: 9 | answer.append(i) 10 | 11 | return answer 12 | -------------------------------------------------------------------------------- /정승호/괄호/solution.py: -------------------------------------------------------------------------------- 1 | a = int(input()) 2 | for i in range(a): 3 | b = input() 4 | s = list(b) 5 | sum = 0 6 | for i in s: 7 | if i == '(': 8 | sum += 1 9 | elif i == ')': 10 | sum -= 1 11 | if sum < 0: 12 | print('NO') 13 | break 14 | if sum > 0: 15 | print('NO') 16 | elif sum == 0: 17 | print('YES') 18 | 19 | -------------------------------------------------------------------------------- /정승호/괄호_변환/solution.py: -------------------------------------------------------------------------------- 1 | def balanceCheck(s): 2 | temp = 0 3 | for i in s: 4 | if i == '(': temp +=1 5 | else : temp -=1 6 | 7 | if temp == 0 : return True 8 | else : return False 9 | 10 | def checkCorrect(s): 11 | stack=[] 12 | for i in s: 13 | if i == '(': 14 | stack.append(i) 15 | else: 16 | if stack: 17 | stack.pop() 18 | else: 19 | return False 20 | return True 21 | 22 | 23 | def solution(p): 24 | answer = '' 25 | u = '' 26 | v = '' 27 | if len(p) == 0 or checkCorrect(p): 28 | return p 29 | for i in range(2,len(p)+1,2): 30 | if balanceCheck(p[0:i]): 31 | u=p[0:i] 32 | v=p[i:len(p)] 33 | break 34 | if checkCorrect(u): 35 | answer+=u+solution(v) 36 | else : 37 | answer+='('+solution(v)+')' 38 | for c in u[1:-1]: 39 | if c=='(': 40 | answer+=')' 41 | else : 42 | answer+='(' 43 | return answer 44 | -------------------------------------------------------------------------------- /정승호/괄호_제거/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | def dfs(index, depth): 6 | global answer, sub_value 7 | 8 | if index == depth: 9 | if ''.join(sub_value) != ''.join(formula): 10 | answer.add(''.join(sub_value)) 11 | return 12 | 13 | is_bracket = formula[index] 14 | if is_bracket == '(': 15 | check[index] = True 16 | dfs(index+1, depth) 17 | check[index] = False 18 | 19 | if is_bracket == ')'and check[pair[index]]: 20 | dfs(index+1, depth) 21 | else: 22 | sub_value.append(is_bracket) 23 | dfs(index+1, depth) 24 | sub_value.pop() 25 | 26 | formula = list(input().strip()) 27 | stack = [] 28 | check = [False for _ in range(len(formula))] 29 | pair = [0 for _ in range(len(formula))] 30 | answer = set() 31 | sub_value = [] 32 | 33 | for index, bracket in enumerate(formula): 34 | if bracket == '(': 35 | stack.append(index) 36 | elif bracket == ')': 37 | pair[index] = stack[-1] 38 | pair[stack[-1]] = index 39 | stack.pop() 40 | 41 | dfs(0, len(formula)) 42 | 43 | print('\n'.join(sorted(answer))) 44 | -------------------------------------------------------------------------------- /정승호/괄호의_값/solution.py: -------------------------------------------------------------------------------- 1 | formula = list(input()) 2 | 3 | stack = [] 4 | answer = 0 5 | 6 | for i in formula: 7 | if i == ')': 8 | temp = 0 9 | while stack: 10 | top = stack.pop() 11 | if top == '(': 12 | if temp == 0: 13 | stack.append(2) 14 | else: 15 | stack.append(2*temp) 16 | break 17 | elif top == '[': 18 | print(0) 19 | exit(0) 20 | else: 21 | temp += int(top) 22 | elif i == ']': 23 | temp = 0 24 | while stack: 25 | top = stack.pop() 26 | if top == '[': 27 | stack.append(3 if temp == 0 else temp*3) 28 | break 29 | elif top == '(': 30 | print(0) 31 | exit(0) 32 | else: 33 | temp += int(top) 34 | else : 35 | stack.append(i) 36 | 37 | for i in stack: 38 | if i == '(' or i == '[': 39 | print(0) 40 | exit(0) 41 | else: 42 | answer += i 43 | print(answer) 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /정승호/구명보트/solution.py: -------------------------------------------------------------------------------- 1 | def solution(people, limit): 2 | answer = 0 3 | i = 0; j = len(people)-1 4 | people.sort() 5 | while i<=j: 6 | answer+=1 7 | if people[i] + people[j] <= limit: 8 | i+=1 9 | j-=1 10 | 11 | return answer 12 | -------------------------------------------------------------------------------- /정승호/균형잡힌_세상/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | input = sys.stdin.readline 5 | 6 | while 1: 7 | string = input().rstrip() 8 | stack = [] 9 | balance = True 10 | for ch in string: 11 | if ch == '(' or ch == '[': 12 | stack.append(ch) 13 | elif ch == ')': 14 | if stack and stack[-1] == '(': 15 | stack.pop() 16 | else: 17 | balance = False 18 | break 19 | elif ch == ']': 20 | if stack and stack[-1] == '[': 21 | stack.pop() 22 | else: 23 | balance = False 24 | break 25 | if string == '.': 26 | break 27 | 28 | print("yes" if balance and len(stack) == 0 else "no") 29 | 30 | 31 | -------------------------------------------------------------------------------- /정승호/기능개발/solution.py: -------------------------------------------------------------------------------- 1 | def solution(progresses, speeds): 2 | answer = [] 3 | N = len(progresses) 4 | done = 0 5 | while N != done: 6 | deploy = 0 7 | for index in range(done, N): 8 | progresses[index] += speeds[index] 9 | 10 | if progresses[done] >= 100: 11 | for i in range(done,N): 12 | if progresses[i] >= 100: 13 | deploy += 1 14 | else: 15 | break 16 | answer.append(deploy) 17 | done += deploy 18 | 19 | return answer 20 | -------------------------------------------------------------------------------- /정승호/나누어_떨어지는_숫자_배열/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arr, divisor): 2 | answer = [] 3 | for i in arr : 4 | if (i >= divisor) and (i % divisor == 0): 5 | answer.append(i) 6 | 7 | if len(answer) == 0: 8 | answer.append(-1) 9 | 10 | answer.sort() 11 | return answer 12 | -------------------------------------------------------------------------------- /정승호/나는야_포켓몬_마스터_이다솜/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N, M = map(int, input().split()) 6 | book = dict() 7 | index_list = [] 8 | for i in range(1, N+1): 9 | poketmon = input().rstrip() 10 | book[poketmon] = i 11 | index_list.append(poketmon) 12 | 13 | for _ in range(M): 14 | query = input().rstrip() 15 | if query.isdigit(): 16 | print(index_list[int(query)-1]) 17 | else: 18 | print(book[query]) 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /정승호/내적/solution.py: -------------------------------------------------------------------------------- 1 | def solution(a, b): 2 | answer = 0 3 | 4 | for i in range(len(a)): 5 | answer += a[i]*b[i] 6 | return answer 7 | -------------------------------------------------------------------------------- /정승호/다리를_지나는_트럭/solution.py: -------------------------------------------------------------------------------- 1 | def solution(bridge_length, weight, truck_weights): 2 | answer = 0 3 | time = 0 4 | wait_queue = [] 5 | bridge = [0]*bridge_length 6 | while len(bridge) != 0: 7 | time += 1 8 | bridge.pop(0) 9 | if truck_weights: 10 | if sum(bridge) + truck_weights[0] <= weight: 11 | bridge.append(truck_weights.pop(0)) 12 | else: 13 | bridge.append(0) 14 | 15 | return time 16 | -------------------------------------------------------------------------------- /정승호/다트게임/solution.py: -------------------------------------------------------------------------------- 1 | def solution(dartResult): 2 | answer = [0] 3 | for s in dartResult: 4 | if s== 'S': 5 | answer[-1] **= 1 6 | answer.append(0) 7 | elif s=='D': 8 | answer[-1] **= 2 9 | answer.append(0) 10 | elif s=='T': 11 | answer[-1]**=3 12 | answer.append(0) 13 | elif s == '*': 14 | answer[-2]*=2 15 | if len(answer) > 2: 16 | answer[-3]*=2 17 | elif s == '#': 18 | answer[-2] *= -1 19 | else: 20 | answer[-1] = answer[-1]*10 + int(s) 21 | 22 | return sum(answer) 23 | -------------------------------------------------------------------------------- /정승호/단지번호붙이기/solution.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | N = int(input()) 4 | 5 | # 방문한 내용 저장 6 | visited = [[0]*N for _ in range(N)] 7 | # 데이터 저장 8 | matrix = [[0]*N for _ in range(N)] 9 | 10 | # 2차원 행렬 저장 11 | for i in range(N): 12 | line = stdin.readline().strip() 13 | for j,b in enumerate(line): 14 | matrix[i][j] = int(b) 15 | 16 | dx = [-1, 1, 0, 0] 17 | dy = [0, 0, 1, -1] 18 | 19 | def dfs(x,y, cnt): 20 | visited[x][y] = 1 21 | global nums 22 | 23 | if matrix[x][y] == 1: 24 | nums += 1 25 | 26 | for i in range(4): 27 | nx = x + dx[i] 28 | ny = y + dy[i] 29 | 30 | if 0 <= nx < N and 0 <= ny < N : 31 | if visited[nx][ny] == 0 and matrix[nx][ny] == 1: 32 | dfs(nx,ny,cnt) 33 | 34 | 35 | cnt = 1 # 아파트 단지 숫자 36 | numlist = [] # 아파트 단지별 숫자 37 | nums = 0 # 아파트의 수 38 | for a in range(N): 39 | for b in range(N): 40 | if matrix[a][b] == 1 and visited[a][b] == 0: 41 | dfs(a,b,cnt) 42 | numlist.append(nums) 43 | nums = 0 44 | 45 | 46 | 47 | print(len(numlist)) 48 | for n in sorted(numlist): 49 | print(n) 50 | -------------------------------------------------------------------------------- /정승호/더_맵게/solution.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | def solution(scoville, K): 3 | answer = 0 4 | data = [] 5 | for s in scoville: 6 | heapq.heappush(data, s) 7 | 8 | while len(data) > 0: 9 | if data[0] >= K: 10 | return answer 11 | a = heapq.heappop(data) 12 | if data != []: 13 | b =heapq.heappop(data) 14 | heapq.heappush(data,a + (b *2)) 15 | answer+=1 16 | 17 | return -1 18 | -------------------------------------------------------------------------------- /정승호/덱/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | deque = [] 5 | N = int(input()) 6 | 7 | for i in range(N): 8 | command = input().split() 9 | cmd = command[0] 10 | if len(command) == 2: 11 | num = command[1] 12 | 13 | # push_front 14 | if cmd == "push_front": deque.insert(0, num) 15 | 16 | # push_back 17 | if cmd == "push_back": deque.append(num) 18 | 19 | # pop_front 20 | elif cmd == "pop_front": 21 | if len(deque) == 0: print(-1) 22 | else : print(deque.pop(0)) 23 | 24 | # pop_back 25 | elif cmd == "pop_back": 26 | if len(deque) == 0: print(-1) 27 | else: print(deque.pop(-1)) 28 | 29 | # size 30 | elif cmd == "size": print(len(deque)) 31 | 32 | # empty 33 | elif cmd == "empty": 34 | if len(deque) == 0: print(1) 35 | else: print(0) 36 | 37 | # front 38 | elif cmd == "front": 39 | if len(deque) == 0: print(-1) 40 | else: print(deque[0]) 41 | 42 | # back 43 | elif cmd == "back": 44 | if len(deque) == 0: print(-1) 45 | else: print(deque[-1]) 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /정승호/두_개_뽑아서_더하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(numbers): 2 | answer = set() 3 | for i in range(len(numbers)): 4 | for j in range(i+1,len(numbers)): 5 | answer.add(numbers[i] + numbers[j]) 6 | answer = sorted(list(answer)) 7 | return answer 8 | -------------------------------------------------------------------------------- /정승호/두_정수_사이의_합/solution.py: -------------------------------------------------------------------------------- 1 | def solution(a, b): 2 | return (abs(a-b) + 1)*(a+b)//2 3 | -------------------------------------------------------------------------------- /정승호/뒤집기/solution.py: -------------------------------------------------------------------------------- 1 | data = input() 2 | count0 = 0 3 | count1 = 0 4 | 5 | if data[0] == '1': 6 | count0 += 1 7 | else : 8 | count1 += 1 9 | 10 | for i in range(len(data)-1): 11 | if data[i] != data[i+1]: 12 | if data[i+1] == '1': 13 | count0 += 1 14 | else : 15 | count1 +=1 16 | 17 | print(min(count0, count1)) 18 | -------------------------------------------------------------------------------- /정승호/로봇_청소기/solution.py: -------------------------------------------------------------------------------- 1 | 2 | # 북,동,남,서 3 | dx = [-1,0,1,0] 4 | dy = [0,1,0,-1] 5 | 6 | 7 | def robot_move(x, y, d): 8 | global ans 9 | if a[x][y] == 0: 10 | a[x][y] = 2 11 | ans += 1 12 | for _ in range(4): 13 | nd = (d + 3) % 4 14 | nx = x + dx[nd] 15 | ny = y + dy[nd] 16 | if a[nx][ny] == 0: 17 | robot_move(nx, ny, nd) 18 | return 19 | d = nd 20 | nd = (d + 2) % 4 21 | nx = x + dx[nd] 22 | ny = y + dy[nd] 23 | if a[nx][ny] == 1: 24 | return 25 | robot_move(nx,ny,d) 26 | 27 | 28 | ans = 0 29 | n, m = map(int, input().split()) 30 | x, y, d = map(int, input().split()) 31 | a = [list(map(int, input().split())) for _ in range(n)] 32 | 33 | robot_move(x,y,d) 34 | print(ans) 35 | 36 | 37 | -------------------------------------------------------------------------------- /정승호/맥주마시면서걸어가기/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | def bfs(x,y): 5 | q,c = deque([[x,y]]), [] 6 | c.append([x,y]) 7 | while q: 8 | x,y = q.popleft() 9 | if x == penta_x and y == penta_y: 10 | print("happy") 11 | return 12 | for nx, ny in d: 13 | if [nx,ny] not in c: 14 | man_distance = abs(x - nx) + abs(y - ny) 15 | if 20*50 >= man_distance: 16 | q.append([nx,ny]) 17 | c.append([nx,ny]) 18 | print("sad") 19 | return 20 | 21 | test_case = int(input()) 22 | for _ in range(test_case): 23 | n = int(input()) # 편의점 갯수 24 | home_x, home_y = map(int, input().split()) 25 | d = [] 26 | for _ in range(n): 27 | x,y = map(int, input().split()) 28 | d.append([x,y]) 29 | penta_x, penta_y = map(int, input().split()) 30 | d.append([penta_x, penta_y]) 31 | bfs(home_x, home_y) 32 | 33 | -------------------------------------------------------------------------------- /정승호/멀쩡한_사각형/solution.py: -------------------------------------------------------------------------------- 1 | import math 2 | def solution(w,h): 3 | return w*h - (w+h-math.gcd(w,h)) 4 | -------------------------------------------------------------------------------- /정승호/문자열_내_p와_y의_개수/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | P_num ,Y_num = 0, 0 3 | s = s.lower() 4 | 5 | for i in s: 6 | if i == 'p': 7 | P_num +=1 8 | elif i == 'y' : 9 | Y_num +=1 10 | 11 | if P_num == Y_num: 12 | return True 13 | 14 | return False 15 | -------------------------------------------------------------------------------- /정승호/문자열_내림차순으로_배치하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | 3 | return ''.join(reversed(sorted(s))) 4 | -------------------------------------------------------------------------------- /정승호/문자열_내맘대로_정렬하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(strings, n): 2 | 3 | return sorted(sorted(strings), key = lambda index : index[n]) 4 | -------------------------------------------------------------------------------- /정승호/문자열_다루기_기본/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | return s.isdigit() and (len(s) == 4 or len(s) == 6) 3 | -------------------------------------------------------------------------------- /정승호/문자열_집합/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N, M = map(int, input().split()) 6 | S = set() 7 | answer = 0 8 | for _ in range(N): 9 | S.add(input()) 10 | 11 | for _ in range(M): 12 | string = input() 13 | if string in S: 14 | answer += 1 15 | 16 | print(answer) 17 | 18 | -------------------------------------------------------------------------------- /정승호/문자열을_정수로_바꾸기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | answer = 0 3 | 4 | for index, num in enumerate(s[::-1]): 5 | if num == '-': 6 | answer *= -1 7 | elif num == '+': 8 | continue 9 | else : 10 | answer += int(num)* (10 ** index) 11 | 12 | return answer 13 | -------------------------------------------------------------------------------- /정승호/미로탐색/solution.py: -------------------------------------------------------------------------------- 1 | n,m = map(int, input().split()) 2 | graph = [] 3 | for i in range(n): 4 | graph.append(list(map(int, input()))) 5 | dx = [-1,1,0,0] 6 | dy = [0,0,-1,1] 7 | 8 | def bfs(x,y): 9 | queue = [] 10 | queue.append((x,y)) 11 | 12 | while queue: 13 | x,y = queue.pop(0) 14 | for i in range(4): 15 | nx = x + dx[i] 16 | ny = y + dy[i] 17 | if nx < 0 or ny < 0 or nx >=n or ny >= m: 18 | continue 19 | if graph[nx][ny] == 0: 20 | continue 21 | if graph[nx][ny]==1: 22 | graph[nx][ny] = graph[x][y]+1 23 | queue.append((nx,ny)) 24 | 25 | return graph[n-1][m-1] 26 | 27 | 28 | print(bfs(0,0)) 29 | -------------------------------------------------------------------------------- /정승호/바이러스/solution.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | T = int(input()) 3 | 4 | graph = [[0] * N for i in range(N)] 5 | visited = [0 * N for i in range(N)] 6 | virus = [] 7 | 8 | 9 | 10 | for i in range(T): 11 | r,c = map(int, input().split()) 12 | graph[r-1][c-1] = 1 13 | graph[c-1][r-1] = 1 14 | 15 | 16 | 17 | 18 | def dfs(V): 19 | virus.append(V) 20 | visited[V-1] = 1 21 | for i in range(N): 22 | if visited[i]==0 and graph[V-1][i] == 1: 23 | dfs(i+1) 24 | 25 | 26 | dfs(1) 27 | 28 | print(len(virus)-1) 29 | -------------------------------------------------------------------------------- /정승호/비밀지도/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n, arr1, arr2): 2 | answer = [] 3 | 4 | for i in range(n): 5 | or_bin = bin(arr1[i] | arr2[i])[2:] 6 | key = '0'*(n-len(or_bin)) + or_bin 7 | answer.append(key.replace('1', '#').replace('0', ' ')) 8 | 9 | return answer 10 | -------------------------------------------------------------------------------- /정승호/상호_평가/solution.py: -------------------------------------------------------------------------------- 1 | def get_score(avg): 2 | if avg >= 90: return 'A' 3 | elif 80 <= avg < 90: return 'B' 4 | elif 70 <= avg < 80: return 'C' 5 | elif 50 <= avg < 70: return 'D' 6 | else : return 'F' 7 | 8 | 9 | def solution(scores): 10 | answer = '' 11 | for j in range(len(scores[0])): 12 | score_sum = 0 13 | my_score_list = [] 14 | 15 | for i in range(len(scores)): 16 | score_sum += scores[i][j] 17 | my_score_list.append(scores[i][j]) 18 | if i == j: 19 | my_score = scores[i][j] 20 | 21 | my_score_list.sort() 22 | 23 | if (my_score_list[0] != my_score_list[1]) and (my_score_list[0] == my_score) : 24 | score_sum -= my_score 25 | answer += get_score(score_sum/((len(scores[0]))-1)) 26 | elif (my_score_list[-1] != my_score_list[-2]) and (my_score_list[-1] == my_score): 27 | score_sum -= my_score 28 | answer += get_score(score_sum/(len(scores[0])-1)) 29 | else: 30 | answer += get_score(score_sum/len(scores[0])) 31 | 32 | 33 | 34 | return answer 35 | -------------------------------------------------------------------------------- /정승호/서울에서_김서방_찾기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(seoul): 2 | answer = "김서방은 " + str(seoul.index("Kim")) + "에 있다" 3 | return answer 4 | -------------------------------------------------------------------------------- /정승호/세용액/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | n = int(input()) 4 | liquid = list(map(int, input().split())) 5 | liquid.sort() 6 | temp = float('inf') 7 | result = [0]*3 # 0에 가까운 값들을 저장 8 | 9 | for i in range(n - 2): 10 | # 중복된 값은 건너뛴다 11 | if i > 0 and liquid[i] == liquid[i - 1]: 12 | continue 13 | 14 | # 간격을 좁혀가며 sum 계산 15 | left, right = i+1, n-1 16 | 17 | while left < right: 18 | total = liquid[i] + liquid[left] + liquid[right] 19 | 20 | if abs(total) < abs(temp): 21 | result[0], result[1], result[2] = liquid[i], liquid[left], liquid[right] 22 | temp = total 23 | 24 | if total < 0: 25 | left += 1 26 | elif total > 0: 27 | right -= 1 28 | else: 29 | # sum = 0인 경우 정답 처리 후 스킵 30 | print(liquid[i], liquid[left], liquid[right]) 31 | sys.exit(0) 32 | 33 | 34 | 35 | for i in result: 36 | print(i, end=' ') 37 | -------------------------------------------------------------------------------- /정승호/소수_찾기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(numbers): 2 | def dfs(word): 3 | if len(word) == k: 4 | result.add(int(word)) 5 | return 6 | 7 | for i in range(n): 8 | if visit[i] == 0: 9 | visit[i] = 1 10 | dfs(word + numbers[i]) 11 | visit[i] = 0 12 | 13 | result = set() 14 | numbers = list(numbers) 15 | n = len(numbers) 16 | visit = [0 for _ in range(n)] 17 | for k in range(1,n+1): 18 | dfs("") 19 | 20 | print(result) 21 | answer = 0 22 | for i in result: 23 | if i == 1 or i == 0: 24 | continue 25 | for j in range(2,i): 26 | if i%j == 0: 27 | break 28 | else: 29 | answer +=1 30 | print(answer) 31 | return answer 32 | -------------------------------------------------------------------------------- /정승호/소수찾기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | num = set(range(2, n+1)) 3 | for i in range(2, n+1): 4 | if i in num: 5 | num -= set(range(2*i, n+1,i)) 6 | return len(num) 7 | -------------------------------------------------------------------------------- /정승호/쇠막대기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arrangement): 2 | answer = 0 3 | stick = 0 4 | steel = list(arrangement) 5 | before = '(' 6 | for i in steel: 7 | if i == '(': 8 | stick +=1 9 | before = i 10 | else: 11 | if before == '(': 12 | stick -=1 13 | answer += stick 14 | before = i 15 | else : 16 | stick -=1 17 | answer +=1 18 | 19 | return answer 20 | -------------------------------------------------------------------------------- /정승호/수_찾기/solution.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | arr_n = list(map(int, input().split())) 3 | arr_n.sort() 4 | M = int(input()) 5 | arr_m = list(map(int, input().split())) 6 | 7 | for i in arr_m: 8 | start = 0 9 | end = N-1 10 | target = i 11 | answer = 0 12 | while(start <= end): 13 | mid = (start+end)//2 14 | if arr_n[mid]==target: 15 | answer = 1 16 | break 17 | elif target < arr_n[mid]: 18 | end = mid-1 19 | else: 20 | start = mid+1 21 | print(answer) 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /정승호/수박수박수박수박수박수/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = '' 3 | 4 | if n%2 == 0: 5 | answer = '수박'*(n//2) 6 | else : 7 | answer = '수박'*(n//2) + '수' 8 | 9 | return answer 10 | -------------------------------------------------------------------------------- /정승호/수식_최대화/solution.py: -------------------------------------------------------------------------------- 1 | def calculate(priority, n, expression): 2 | if n == 2: 3 | return str(eval(expression)) 4 | if priority[n]=='*': 5 | res = eval('*'.join([calculate(priority, n+1, e) for e in expression.split('*')])) 6 | if priority[n] == '+': 7 | res = eval('+'.join([calculate(priority, n + 1, e) for e in expression.split('+')])) 8 | if priority[n] == '-': 9 | res = eval('-'.join([calculate(priority, n + 1, e) for e in expression.split('-')])) 10 | return str(res) 11 | 12 | 13 | def solution(expression): 14 | answer = 0 15 | priorities = [ 16 | ('*', '-', '+'), 17 | ('*', '+', '-'), 18 | ('+', '*', '-'), 19 | ('+', '-', '*'), 20 | ('-', '*', '+'), 21 | ('-', '+', '*') 22 | ] 23 | for priority in priorities: 24 | res = int(calculate(priority, 0, expression)) 25 | answer = max(answer, abs(res)) 26 | 27 | return answer 28 | -------------------------------------------------------------------------------- /정승호/숨바꼭질/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | N, K = map(int, input().split()) 4 | visited = [False]*100001 5 | 6 | def bfs(V): 7 | count = 0 8 | q = deque([[V, count]]) 9 | while q: 10 | v = q.popleft() 11 | currentPosition = v[0] 12 | count = v[1] 13 | if not visited[currentPosition]: 14 | visited[currentPosition] = True 15 | if currentPosition == K: 16 | return count 17 | count += 1 18 | 19 | if (currentPosition * 2) <= 100000: 20 | q.append([currentPosition*2, count]) 21 | if (currentPosition +1) <= 100000: 22 | q.append([currentPosition+1,count]) 23 | if (currentPosition - 1) >= 0: 24 | q.append([currentPosition-1, count]) 25 | 26 | return count 27 | 28 | print(bfs(N)) 29 | -------------------------------------------------------------------------------- /정승호/스킬트리/solution.py: -------------------------------------------------------------------------------- 1 | def solution(skill, skill_trees): 2 | answer = 0 3 | for skills in skill_trees: 4 | skill_list=list(skill) 5 | for i in skills: 6 | if i in skill: 7 | if i != skill_list.pop(0): #skill에 포함되는 값이 skill의 첫번째 요소와 일치하는지 8 | break 9 | else: #for - else 문은 break에 걸리지 않고 끝까지 시행됬을때 작동한다 10 | answer+=1 11 | return answer 12 | -------------------------------------------------------------------------------- /정승호/스타트링크/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | F, S, G, U, D = map(int, input().split()) 4 | 5 | 6 | def bfs(F,S,G,U,D): 7 | visited = {S} 8 | q = deque([[S,0]]) 9 | 10 | while q: 11 | currentFloor, count = q.popleft() 12 | if currentFloor == G: 13 | return count 14 | if currentFloor + U <= F and (currentFloor + U) not in visited: 15 | q.append([currentFloor + U, count + 1]) 16 | visited.add(currentFloor+U) 17 | if currentFloor - D >0 and (currentFloor - D) not in visited: 18 | q.append([currentFloor-D,count+1]) 19 | visited.add(currentFloor-D) 20 | 21 | return "use the stairs" 22 | 23 | print(bfs(F,S,G,U,D)) 24 | -------------------------------------------------------------------------------- /정승호/스택/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def input(): 5 | return sys.stdin.readline().rstrip() 6 | 7 | N = int(input()) 8 | stack = [] 9 | for i in range(N): 10 | order = input().split() 11 | cmd = order[0] 12 | if len(order) == 2: 13 | num = order[1] 14 | 15 | # push 16 | if cmd == "push": 17 | stack.append(num) 18 | # pop 19 | elif cmd == "pop": 20 | if len(stack) == 0: 21 | print("-1") 22 | else: 23 | print(stack.pop(-1)) 24 | 25 | # top 26 | elif cmd == "top": 27 | if len(stack) == 0: 28 | print("-1") 29 | else: 30 | print(stack[-1]) 31 | 32 | # size 33 | elif cmd == "size": 34 | print(len(stack)) 35 | 36 | # empty 37 | else: 38 | if len(stack) == 0: 39 | print("1") 40 | else : 41 | print("0") 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /정승호/스택_수열/solution.py: -------------------------------------------------------------------------------- 1 | 2 | n = int(input()) 3 | stack = [] 4 | count = 0 5 | result = [] 6 | flag = True 7 | 8 | for _ in range(n): 9 | num = int(input()) 10 | while count < num: 11 | count += 1 12 | stack.append(count) 13 | result.append('+') 14 | 15 | if stack[-1] == num: 16 | stack.pop() 17 | result.append('-') 18 | else: 19 | flag = False 20 | break 21 | 22 | if not flag: 23 | print("NO") 24 | else: 25 | for i in result : 26 | print(i) 27 | 28 | -------------------------------------------------------------------------------- /정승호/시공의폭풍속으로/solution.py: -------------------------------------------------------------------------------- 1 | teamInput = list(map(int, input().split(" "))) 2 | myChoice = list(map(int,input().split(" "))) 3 | 4 | hero = [0]*100 5 | answer = 0 6 | for i in teamInput: 7 | hero[i] += 1 8 | 9 | for j in myChoice: 10 | if hero[j] == 0: 11 | answer +=1 12 | 13 | print(answer) 14 | 15 | #goorm 16 | -------------------------------------------------------------------------------- /정승호/실패율/solution.py: -------------------------------------------------------------------------------- 1 | def solution(N, stages): 2 | remain_user = len(stages) 3 | answer = {} 4 | for stage in range(1,N+1): 5 | if remain_user != 0: 6 | count = stages.count(stage) 7 | answer[stage] = count/remain_user 8 | remain_user -= count 9 | else: 10 | answer[stage] = 0 11 | 12 | return sorted(answer, key = lambda x : answer[x], reverse = True) 13 | -------------------------------------------------------------------------------- /정승호/아기_상어/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from pprint import pprint 3 | N = int(input()) 4 | ocean = [list(map(int, input().split()))for _ in range(N)] 5 | direction = [[0,1],[-1,0],[1,0],[0,-1]] 6 | start_point = [-1,-1] 7 | 8 | def bfs(): 9 | q = deque([[start_point[0], start_point[1]]]) 10 | visited = [[start_point[0],start_point[1]]] 11 | answer = 0 12 | 13 | shark_size = 2 14 | shark_feed = 0 15 | shark_time = 0 16 | eat_flag = False 17 | 18 | while q: 19 | if q: 20 | q = deque(sorted(q, key=lambda k:[k[1], k[0]])) 21 | 22 | qsize = len(q) 23 | for _ in range(qsize): 24 | x,y = q.popleft() 25 | 26 | if 0 < ocean[y][x] < shark_size: 27 | ocean[y][x] = 0 28 | shark_feed+=1 29 | if shark_feed==shark_size: 30 | shark_size+=1 31 | shark_feed=0 32 | 33 | q = deque() 34 | visited = [[x,y]] 35 | answer = shark_time 36 | eat_flag=True 37 | 38 | for dx,dy in direction: 39 | nx, ny = x+dx, y+dy 40 | if 0<=nx< N and 0<=ny h: 22 | visited[nx][ny] = True 23 | dfs(nx,ny,h) 24 | 25 | answer = 0 26 | 27 | for k in range(max_val+1): 28 | visited = [[False] * N for _ in range(N)] 29 | safety = 0 30 | 31 | for i in range(N): 32 | for j in range(N): 33 | if matrix[i][j] > k and not visited[i][j]: 34 | safety +=1 35 | visited[i][j] = True 36 | dfs(i,j,k) 37 | 38 | answer = max(answer, safety) 39 | 40 | print(answer) 41 | -------------------------------------------------------------------------------- /정승호/약수의_합/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = 0 3 | for i in range(1, (n//2) +1): 4 | if n%i == 0: 5 | answer += i 6 | 7 | return answer + n 8 | -------------------------------------------------------------------------------- /정승호/예산/solution.py: -------------------------------------------------------------------------------- 1 | def solution(d, budget): 2 | answer = 0 3 | temp = 0 4 | d.sort() 5 | for i in d: 6 | temp += i 7 | if temp <= budget: 8 | answer+=1 9 | else : 10 | break 11 | 12 | return answer 13 | -------------------------------------------------------------------------------- /정승호/완주하지_못한_선수/solution.py: -------------------------------------------------------------------------------- 1 | def solution(participant, completion): 2 | answer = '' 3 | participant.sort() 4 | completion.sort() 5 | 6 | for i in range(len(completion)): 7 | if participant[i] != completion[i]: 8 | answer = participant[i] 9 | break 10 | 11 | if len(answer) == 0: 12 | answer = participant[-1] 13 | 14 | return answer 15 | -------------------------------------------------------------------------------- /정승호/요세푸스_문제/solution.py: -------------------------------------------------------------------------------- 1 | 2 | N, K = map(int, input().split()) 3 | arr = [i for i in range(1, N+1)] 4 | 5 | answer = [] 6 | num = 0 7 | 8 | for i in range(N): 9 | num += K-1 10 | if num >= len(arr): 11 | num = num % len(arr) 12 | answer.append(str(arr.pop(num))) 13 | 14 | print("<",", ".join(answer)[:],">", sep="") 15 | 16 | -------------------------------------------------------------------------------- /정승호/위장/solution.py: -------------------------------------------------------------------------------- 1 | def solution(clothes): 2 | closet = {} 3 | result = 1 4 | for element in clothes: 5 | key = element[1] 6 | value = element[0] 7 | if key in closet: 8 | closet[key].append(value) 9 | else: 10 | closet[key] = [value] 11 | 12 | for key in closet.keys(): 13 | result = result * (len(closet[key]) + 1) 14 | return result - 1 15 | -------------------------------------------------------------------------------- /정승호/이상한_문자_만들기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(s): 2 | new_s = s.split(' ') 3 | answer = '' 4 | for word in new_s: 5 | for i, spell in enumerate(word): 6 | answer += spell.upper() if i % 2 == 0 else spell.lower() 7 | answer += ' ' 8 | return answer[:-1] 9 | -------------------------------------------------------------------------------- /정승호/자릿수_더하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = 0 3 | while n != 0: 4 | answer += n%10 5 | n = n//10 6 | return answer 7 | -------------------------------------------------------------------------------- /정승호/자연수_뒤집어_배열로_만들기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | answer = [] 3 | while n != 0: 4 | answer.append(n%10) 5 | n = n//10 6 | return answer 7 | -------------------------------------------------------------------------------- /정승호/전화번호_목록/solution.py: -------------------------------------------------------------------------------- 1 | def solution(phone_book): 2 | answer = True 3 | hash_map = {} 4 | for phone_number in phone_book: 5 | hash_map[phone_number] = 1 6 | for phone_number in phone_book: 7 | temp = "" 8 | for number in phone_number: 9 | temp += number 10 | if temp in hash_map and temp != phone_number: 11 | return False 12 | return answer 13 | -------------------------------------------------------------------------------- /정승호/정수_내림차순으로_배치하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | nList = list(map(int, str(n))) 3 | newL = sorted(nList, reverse = True) 4 | strings = [str(i) for i in newL] 5 | a_string = "".join(strings) 6 | 7 | return int(a_string) 8 | -------------------------------------------------------------------------------- /정승호/정수_제곱근_판별/solution.py: -------------------------------------------------------------------------------- 1 | def solution(n): 2 | num = pow(n, 0.5) 3 | if num == int(num): 4 | return pow(num+1, 2) 5 | 6 | return -1 7 | -------------------------------------------------------------------------------- /정승호/제일_작은수_제거하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arr): 2 | answer = [] 3 | if len(arr) == 1: 4 | return [-1] 5 | arr.remove((min(arr))) 6 | return arr 7 | -------------------------------------------------------------------------------- /정승호/조이스틱/solution.py: -------------------------------------------------------------------------------- 1 | def solution(name): 2 | answer = 0 3 | name=list(name) 4 | index=0 5 | while(True): 6 | right=1 7 | left=1 8 | if name[index] != 'A': 9 | updown = min(ord(name[index])-ord('A'),(ord('Z')-ord(name[index])+1)) 10 | answer += updown 11 | name[index] = 'A' 12 | if name == ["A"]*len(name): break 13 | for i in range(1,len(name)): 14 | if name[index+i]=="A": right+=1 15 | else: break 16 | for i in range(1,len(name)): 17 | if name[index-i]=="A": left+=1 18 | else: break 19 | if right>left: 20 | answer+=left 21 | index-=left 22 | else: 23 | answer+=right 24 | index+=right 25 | return answer 26 | -------------------------------------------------------------------------------- /정승호/좋은_단어/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N = int(input()) 6 | answer = 0 7 | 8 | for _ in range(N): 9 | word_list = input().rstrip() 10 | stack = [] 11 | 12 | for ch in word_list: 13 | 14 | if stack and stack[-1] == ch: 15 | stack.pop() 16 | 17 | else: stack.append(ch) 18 | 19 | if not stack: 20 | answer += 1 21 | 22 | 23 | print(answer) 24 | -------------------------------------------------------------------------------- /정승호/주식가격/soluton.py: -------------------------------------------------------------------------------- 1 | def solution(prices): 2 | l = len(prices) 3 | a = [0]*l 4 | for i in range(l-1): 5 | for j in range(i+1, l): 6 | if prices[i] > prices[j]: 7 | break; 8 | a[i] = j-i 9 | return a 10 | 11 | -------------------------------------------------------------------------------- /정승호/직업군_추천하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(table, languages, preference): 2 | answer = [] 3 | new_table = sorted([list(t.split()) for t in table], key=lambda x : x[0]) 4 | preference_table = {n : new_table[n][0] for n in range(len(new_table))} 5 | 6 | for i in range(len(preference_table)): 7 | total = 0 8 | for lang, pref in zip(languages, preference): 9 | if lang in new_table[i]: 10 | total += (6 - new_table[i].index(lang)) * pref 11 | answer.append(total) 12 | return preference_table[answer.index(max(answer))] 13 | 14 | -------------------------------------------------------------------------------- /정승호/짝수와_홀수/solution.py: -------------------------------------------------------------------------------- 1 | def solution(num): 2 | if num%2 == 0 : 3 | return "Even" 4 | return "Odd" 5 | -------------------------------------------------------------------------------- /정승호/촌수계산/solution.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | from collections import defaultdict 3 | 4 | n = int(input()) 5 | a,b = map(int, input().split()) 6 | m = int(input()) 7 | 8 | d= defaultdict(set) 9 | 10 | for _ in range(m): 11 | x, y = map(int, input().split()) 12 | d[x].add(y) 13 | d[y].add(x) 14 | 15 | def bfs(a,b): 16 | queue, visited = [a], {a} 17 | step = 0 18 | while queue: 19 | size = len(queue) 20 | for i in range(size): 21 | cur = queue.pop(0) 22 | if cur == b: 23 | return step 24 | for j in d[cur]: 25 | if j not in visited: 26 | visited.add(j) 27 | queue.append(j) 28 | 29 | step += 1 30 | 31 | return -1 32 | 33 | 34 | print(bfs(a,b)) 35 | 36 | 37 | -------------------------------------------------------------------------------- /정승호/최대_힙/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import heapq 3 | 4 | input = sys.stdin.readline 5 | 6 | N = int(input()) 7 | exp = [] 8 | for _ in range(N): 9 | exp.append(int(input())) 10 | 11 | heap = [] 12 | heapq.heapify(heap) 13 | for i in exp: 14 | if i == 0 and len(heap)==0: 15 | print(0) 16 | elif i == 0: 17 | print(abs(heapq.heappop(heap))) 18 | else: 19 | heapq.heappush(heap, -i) 20 | 21 | -------------------------------------------------------------------------------- /정승호/최대공약수와_최소공배수/solution.py: -------------------------------------------------------------------------------- 1 | def gcb(a,b): 2 | i = min(a,b) 3 | while True: 4 | if a%i == 0 and b%i == 0: 5 | return i 6 | i-=1 7 | 8 | 9 | def solution(n, m): 10 | return [gcb(n,m), n*m//gcb(n,m)] 11 | -------------------------------------------------------------------------------- /정승호/치킨_배달/solution.py: -------------------------------------------------------------------------------- 1 | def dfs(idx, selected_chicken): 2 | global answer 3 | 4 | if idx > len(chicken): 5 | return 6 | if selected_chicken == M: 7 | result = 0 8 | for house in houses: 9 | min_dist = 99999999 10 | for chicken_idx, value in enumerate(chicken): 11 | if not is_checked[chicken_idx]: 12 | continue 13 | min_dist = min(min_dist, (abs(house[0]-value[0])+abs(house[1]-value[1]))) 14 | result += min_dist 15 | answer = min(result, answer) 16 | return 17 | is_checked[idx] = True 18 | dfs(idx+1, selected_chicken+1) 19 | is_checked[idx] = False 20 | dfs(idx+1, selected_chicken) 21 | 22 | 23 | 24 | 25 | N, M = map(int, input().split()) 26 | city = [list(map(int, input().split())) for _ in range(N)] 27 | houses = [] 28 | chicken = [] 29 | answer = 99999999 30 | 31 | for i in range(N): 32 | for j in range(N): 33 | if city[i][j] == 1: 34 | houses.append([i+1, j+1]) 35 | elif city[i][j] == 2: 36 | chicken.append([i+1, j+1]) 37 | 38 | is_checked = [False]*(len(chicken)+1) 39 | dfs(0,0) 40 | print(answer) 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /정승호/카드2/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | N = int(input()) 3 | arr = deque([i for i in range(1, N+1)]) 4 | 5 | while True: 6 | tmp = arr.popleft() 7 | if not arr: 8 | print(tmp) 9 | break 10 | arr.append(arr.popleft()) 11 | 12 | -------------------------------------------------------------------------------- /정승호/카드_놓기_18115/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | import sys 3 | 4 | input = sys.stdin.readline 5 | 6 | N = int(input()) 7 | rule = deque(map(int, input().split())) 8 | after = deque(range(1, N+1)) 9 | before = deque() 10 | while rule: 11 | t = rule.pop() 12 | a = after.popleft() 13 | if t == 1: 14 | before.appendleft(a) 15 | elif t == 2: 16 | before.insert(1,a) 17 | elif t == 3: 18 | before.append(a) 19 | 20 | print(*before) 21 | 22 | 23 | -------------------------------------------------------------------------------- /정승호/카펫/solution.py: -------------------------------------------------------------------------------- 1 | def solution(brown, yellow): 2 | s = brown + yellow 3 | for i in range(s,2,-1): 4 | if s%i == 0: 5 | a = s//i 6 | if yellow == (a-2)*(i-2): 7 | return [i,a] 8 | -------------------------------------------------------------------------------- /정승호/콜라츠_추측/solution.py: -------------------------------------------------------------------------------- 1 | def solution(num): 2 | answer = 0 3 | if num == 1: 4 | return 0 5 | while True: 6 | num = num/2 if num % 2 == 0 else (num*3)+1 7 | answer += 1 8 | if num == 1: 9 | return answer 10 | elif answer == 500: 11 | return -1 12 | return answer 13 | 14 | -------------------------------------------------------------------------------- /정승호/쿼드압축_후_숫자세기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arr): 2 | answer = [0,0] 3 | N = len(arr) 4 | 5 | def comp(x,y,n): 6 | init = arr[x][y] 7 | for i in range(x, x+n): 8 | for j in range(y, y+n): 9 | if arr[i][j] != init: 10 | nn = n//2 11 | comp(x,y,nn) 12 | comp(x+nn,y,nn) 13 | comp(x,y+nn,nn) 14 | comp(x+nn,y+nn,nn) 15 | return 16 | answer[init] +=1 17 | comp(0,0,N) 18 | return answer 19 | 20 | -------------------------------------------------------------------------------- /정승호/큐/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | 4 | input = sys.stdin.readline 5 | 6 | N = int(input()) 7 | queue = deque() 8 | 9 | for _ in range(N): 10 | cmd = input().split() 11 | 12 | if cmd[0] == "push": 13 | queue.append(cmd[1]) 14 | 15 | elif cmd[0] == "pop": 16 | if len(queue) != 0: print(queue.popleft()) 17 | else: print(-1) 18 | 19 | elif cmd[0] == "size": 20 | print(len(queue)) 21 | 22 | elif cmd[0] == "empty": 23 | if len(queue) == 0: print(1) 24 | else: print(0) 25 | 26 | elif cmd[0] == "front": 27 | if len(queue) == 0: print(-1) 28 | else: print(queue[0]) 29 | 30 | elif cmd[0] == "back": 31 | if len(queue) == 0: print(-1) 32 | else: print(queue[-1]) 33 | 34 | -------------------------------------------------------------------------------- /정승호/큐_2/solution.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | T = input() 3 | queue, commands = [], stdin.readlines() 4 | index = 0 5 | 6 | for command in commands: 7 | cmd = command.split() 8 | 9 | # push 10 | if cmd[0] == "push": 11 | queue.append(cmd[1]) 12 | 13 | # pop 14 | elif cmd[0] == "pop": 15 | if len(queue) > index: 16 | print(queue[index]) 17 | index += 1 18 | else: print(-1) 19 | 20 | # size 21 | elif cmd[0] == "size": 22 | print(len(queue)-index) 23 | 24 | # empty 25 | elif cmd[0] == "empty": 26 | if len(queue) == index: 27 | print(1) 28 | index = 0 29 | queue = [] 30 | else: print(0) 31 | 32 | # front 33 | elif cmd[0] == "front": 34 | if len(queue) > index : print(queue[index]) 35 | else: print(-1) 36 | 37 | # back 38 | elif cmd[0] == "back": 39 | if len(queue) > index: print(queue[-1]) 40 | else: print(-1) 41 | 42 | -------------------------------------------------------------------------------- /정승호/크레인_인형뽑기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(board, moves): 2 | answer = 0 3 | basket = [] 4 | 5 | for i in moves: 6 | for j in range(len(board)): 7 | if board[j][i-1] != 0: 8 | basket.append(board[j][i-1]) 9 | board[j][i-1] = 0 10 | 11 | if (basket[len(basket)-1] == basket[len(basket)-2]) and len(basket) >= 2 : 12 | basket.pop() 13 | basket.pop() 14 | answer += 2 15 | break 16 | 17 | return answer 18 | -------------------------------------------------------------------------------- /정승호/큰수만들기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(number, k): 2 | stack = [] 3 | for index, num in enumerate(number): 4 | while stack and stack[-1] < num and k >0: 5 | stack.pop() 6 | k-=1 7 | 8 | if k ==0: 9 | stack += number[index:] 10 | break 11 | stack.append(num) 12 | if k > 0: 13 | stack = stack[:-k] 14 | answer = "".join(stack) 15 | return answer 16 | -------------------------------------------------------------------------------- /정승호/키로거/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N = int(input()) 6 | 7 | for _ in range(N): 8 | pass_word = input().rstrip() 9 | left_stack = [] 10 | right_stack = [] 11 | 12 | for word in pass_word: 13 | if word == '<': 14 | if left_stack: 15 | right_stack.append(left_stack.pop()) 16 | elif word == '>': 17 | if right_stack: 18 | left_stack.append(right_stack.pop()) 19 | elif word == '-': 20 | if left_stack: 21 | left_stack.pop() 22 | else: left_stack.append(word) 23 | 24 | left_stack.extend(reversed(right_stack)) 25 | print(''.join(left_stack)) 26 | -------------------------------------------------------------------------------- /정승호/키패드_누르기/solution.py: -------------------------------------------------------------------------------- 1 | def get_distance(hand,number): 2 | location = { 3 | '1' : (0,0), '2' : (0,1), '3' : (0,2), 4 | '4' : (1,0), '5' : (1,1), '6' : (1,2), 5 | '7' : (2,0), '8' : (2,1), '9' : (2,2), 6 | '*' : (3,0), '0' : (3,1), '#' : (3,2) 7 | } 8 | number = str(number) 9 | x_hand, y_hand = location[hand] 10 | x_num, y_num = location[number] 11 | return abs(x_hand - x_num) + abs(y_hand - y_num) 12 | 13 | 14 | def solution(numbers, hand): 15 | answer = '' 16 | left_thumb = '*' 17 | right_thumb = '#' 18 | hand = 'R' if hand == 'right' else 'L' 19 | 20 | for i in numbers: 21 | if i in [1,4,7]: 22 | answer+='L' 23 | left_thumb = str(i) 24 | continue 25 | elif i in [3,6,9]: 26 | answer+='R' 27 | right_thumb = str(i) 28 | continue 29 | else: 30 | dis1 = get_distance(left_thumb, i) 31 | dis2 = get_distance(right_thumb, i) 32 | if dis1 > dis2: 33 | answer += 'R' 34 | right_thumb = str(i) 35 | if dis1 < dis2: 36 | answer += 'L' 37 | left_thumb = str(i) 38 | if dis1 == dis2: 39 | answer += hand 40 | if hand == 'R': 41 | right_thumb = str(i) 42 | if hand == 'L': 43 | left_thumb = str(i) 44 | 45 | return answer 46 | -------------------------------------------------------------------------------- /정승호/타겟_넘버/solution.py: -------------------------------------------------------------------------------- 1 | def solution(numbers, target): 2 | n = len(numbers) 3 | answer = 0 4 | def dfs(idx, result): 5 | if idx == n: 6 | if result == target: 7 | nonlocal answer 8 | answer += 1 9 | return 10 | else: 11 | dfs(idx+1, result+numbers[idx]) 12 | dfs(idx+1, result-numbers[idx]) 13 | dfs(0,0) 14 | return answer 15 | -------------------------------------------------------------------------------- /정승호/탑/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | n = int(sys.stdin.readline()) 3 | tower = list(map(int, sys.stdin.readline().split())) 4 | stack = [] 5 | goto = [0] * n 6 | for i in range(n): 7 | t = tower[i] 8 | while stack and tower[stack[-1]] < t: 9 | stack.pop() 10 | if stack: 11 | goto[i] = stack[-1] + 1 12 | stack.append(i) 13 | 14 | print(' '.join(list(map(str, goto)))) 15 | 16 | -------------------------------------------------------------------------------- /정승호/토마토/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import deque 3 | input = sys.stdin.readline 4 | m,n,h = map(int, input().split()) 5 | s = [[] for _ in range(h)] 6 | visited = [[[0 for _ in range(m)] for _ in range(n)] for _ in range(h)] 7 | q = deque() 8 | isTrue = False 9 | st = False 10 | dx = [1,-1,0,0,0,0] 11 | dy = [0,0,-1,1,0,0] 12 | dz = [0,0,0,0,-1,1] 13 | 14 | def bfs(): 15 | while q: 16 | a,b,c = q.popleft() 17 | visited[c][a][b] = 1 18 | for i in range(6): 19 | x = a + dx[i] 20 | y = b + dy[i] 21 | z = c + dz[i] 22 | if 0 <= x < n and 0<= y < m and 0<= z < h \ 23 | and s[z][x][y]==0 and visited[z][x][y] == 0: 24 | q.append([x,y,z]) 25 | s[z][x][y] = s[c][a][b] +1 26 | visited[z][x][y] = 1 27 | 28 | 29 | for i in range(h): 30 | for j in range(n): 31 | s[i].append(list(map(int, input().split()))) 32 | 33 | 34 | for z in range(h): 35 | for x in range(n): 36 | for y in range(m): 37 | if s[z][x][y] == 1: 38 | q.append([x,y,z]) 39 | 40 | 41 | bfs() 42 | max_num = 0 43 | for z in range(h): 44 | for x in range(n): 45 | for y in range(m): 46 | if s[z][x][y] == 0: 47 | isTrue = True 48 | max_num = max(max_num, s[z][x][y]) 49 | 50 | if isTrue: 51 | print(-1) 52 | else : 53 | print(max_num - 1) 54 | 55 | 56 | -------------------------------------------------------------------------------- /정승호/파이프_옮기기_1/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | read = sys.stdin.readline 3 | 4 | N = int(read()) 5 | board = [list(map(int, read().split())) for _ in range(N)] 6 | dp = [[[0 for _ in range(N)] for _ in range(N)] for _ in range(3)] 7 | 8 | # 0 -, 1 \, 2 | 9 | dp[0][0][1] = 1 10 | for i in range(2, N): 11 | if board[0][i] == 0: 12 | dp[0][0][i] = dp[0][0][i-1] 13 | 14 | for r in range(1, N): 15 | for c in range(1, N): 16 | if board[r][c] == 0 and board[r][c-1] == 0 and board[r-1][c] == 0: 17 | dp[1][r][c] = dp[0][r-1][c-1] + dp[1][r-1][c-1] + dp[2][r-1][c-1] 18 | 19 | if board[r][c] == 0: 20 | dp[0][r][c] = dp[0][r][c-1] + dp[1][r][c-1] 21 | dp[2][r][c] = dp[2][r-1][c] + dp[1][r-1][c] 22 | 23 | print(sum(dp[i][N-1][N-1] for i in range(3))) 24 | -------------------------------------------------------------------------------- /정승호/평균_구하기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arr): 2 | answer = sum(arr)/len(arr) 3 | return answer 4 | -------------------------------------------------------------------------------- /정승호/평범한배낭/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | N, K = map(int, input().split()) 4 | stuff = [[0,0]] 5 | knapsack = [[0 for _ in range(K + 1)] for _ in range(N + 1)] 6 | 7 | for _ in range(N): 8 | stuff.append(list(map(int, input().split()))) 9 | 10 | 11 | #냅색 문제 풀이 12 | for i in range(1, N + 1): 13 | for j in range(1, K + 1): 14 | weight = stuff[i][0] 15 | value = stuff[i][1] 16 | 17 | if j < weight: 18 | knapsack[i][j] = knapsack[i - 1][j] #weight보다 작으면 위의 값을 그대로 가져온다 19 | else: 20 | knapsack[i][j] = max(value + knapsack[i - 1][j - weight], knapsack[i - 1][j]) 21 | 22 | print(knapsack[N][K] 23 | -------------------------------------------------------------------------------- /정승호/풍선_터뜨리기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(a): 2 | answer = 2 3 | if 0 <= len(a) <= 2: 4 | return len(a) 5 | temp = set() 6 | left, right = a[0], a[-1] 7 | for i in range(1, len(a)-1): 8 | if left > a[i]: 9 | temp.add(a[i]) 10 | left = a[i] 11 | if right > a[-1-i]: 12 | temp.add(a[-1-i]) 13 | right = a[-1-i] 14 | 15 | return answer + len(temp) 16 | -------------------------------------------------------------------------------- /정승호/풍선_터뜨리기_BOJ/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N = int(input()) 6 | ballons = list(map(int, input().split())) 7 | result = [] 8 | index = [i for i in range(1, N+1)] 9 | ballon_num = ballons.pop(0) 10 | result.append(index.pop(0)) 11 | idx = 0 12 | 13 | while ballons: 14 | if ballon_num < 0: 15 | idx = (idx + ballon_num) % len(ballons) 16 | else: 17 | idx = (idx + (ballon_num-1)) % len(ballons) 18 | ballon_num = ballons.pop(idx) 19 | result.append(index.pop(idx)) 20 | 21 | for r in result: 22 | print(r, end=' ') 23 | -------------------------------------------------------------------------------- /정승호/프린터_큐/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | import sys 3 | 4 | input = sys.stdin.readline 5 | N = int(input()) 6 | 7 | 8 | for i in range(N): 9 | n, m = map(int, input().split()) 10 | queue = deque(list(map(int, input().split()))) 11 | count = 0 12 | while queue: 13 | big = max(queue) 14 | front = queue.popleft() 15 | m-=1 16 | if big == front: 17 | count += 1 18 | if m < 0: 19 | print(count) 20 | break 21 | else: 22 | queue.append(front) 23 | if m < 0: 24 | m = len(queue)-1 25 | 26 | -------------------------------------------------------------------------------- /정승호/하노이탑/solution.py: -------------------------------------------------------------------------------- 1 | def hanoi(n, origin, destination, buffer): 2 | if n == 0: 3 | return 4 | # n-1개의 원판을 1번 막대에서 2번 막대로 이동 5 | hanoi(n-1, origin, buffer, destination) 6 | print(origin, destination) 7 | # n-1개의 원판을 2번에서 3번 막대로 이동 8 | hanoi(n-1,buffer, destination, origin) 9 | 10 | k = int(input()) 11 | print(2**k - 1) 12 | hanoi(k,1,3,2) 13 | -------------------------------------------------------------------------------- /정승호/하샤드_수/solution.py: -------------------------------------------------------------------------------- 1 | def solution(x): 2 | answer = True 3 | temp = 0 4 | y = x 5 | 6 | while y != 0: 7 | temp += y%10 8 | y = y//10 9 | 10 | if x%temp != 0: 11 | return False 12 | 13 | return answer 14 | -------------------------------------------------------------------------------- /정승호/핸드폰_번호_가리기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(phone_number): 2 | answer = (len(phone_number)-4)* '*' + phone_number[-4:] 3 | return answer 4 | -------------------------------------------------------------------------------- /정승호/행렬의_덧셈/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arr1, arr2): 2 | answer = [] 3 | for i in range(len(arr1)): 4 | temp = [] 5 | for j in range(len(arr1[0])): 6 | total = arr1[i][j] + arr2[i][j] 7 | temp.append(total) 8 | answer.append(temp) 9 | 10 | return answer 11 | -------------------------------------------------------------------------------- /정승호/회전하는_큐/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N, M = map(int, input().split()) 6 | arr = list(map(int, input().split())) 7 | queue = [i for i in range(1, N+1)] 8 | answer = 0 9 | 10 | for target in arr: 11 | index = queue.index(target) 12 | if len(queue)//2 >= index: answer += index 13 | else: answer += len(queue) - index 14 | queue = queue[index + 1:] + queue[:index] 15 | 16 | print(answer) 17 | 18 | -------------------------------------------------------------------------------- /정승호/후보_추천하기/solution.py: -------------------------------------------------------------------------------- 1 | 2 | N = int(input()) 3 | total_reco = int(input()) 4 | reco_student = list(map(int, input().split())) 5 | frame = {} 6 | cnt = 0 7 | 8 | for i in range(total_reco): 9 | if reco_student[i] in frame: 10 | frame[reco_student[i]][0] += 1 11 | else: 12 | if len(frame) < N: 13 | frame[reco_student[i]] = [1,i] 14 | else: 15 | del_list = sorted(frame.items(), key= lambda x : (x[1][0], x[1][1])) 16 | del_key = del_list[0][0] 17 | del(frame[del_key]) 18 | frame[reco_student[i]] = [1,i] 19 | 20 | ans_list = list(sorted(frame.keys())) 21 | print(*ans_list) 22 | 23 | -------------------------------------------------------------------------------- /정승호/후위_표기식/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | input = sys.stdin.readline 5 | stack = [] 6 | result = '' 7 | 8 | formula = list(input().strip()) 9 | 10 | for s in formula: 11 | if s.isalpha(): 12 | result += s 13 | 14 | else: 15 | if s == '(': 16 | stack.append(s) 17 | elif s == '*' or s == '/': 18 | while stack and (stack[-1] == '*' or stack[-1] == '/'): 19 | result += stack.pop() 20 | stack.append(s) 21 | elif s == '+' or s == '-': 22 | while stack and stack[-1] != '(': 23 | result += stack.pop() 24 | stack.append(s) 25 | 26 | elif s == ')': 27 | while stack and stack[-1] != '(': 28 | result += stack.pop() 29 | stack.pop() 30 | 31 | while stack: 32 | result += stack.pop() 33 | 34 | print(result) 35 | 36 | -------------------------------------------------------------------------------- /정승호/후위_표기식2/solution.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | input = sys.stdin.readline 4 | 5 | N = int(input()) 6 | 7 | formula = input().split() 8 | 9 | alpha = [0]*N 10 | stack = [] 11 | for i in range(N): 12 | alpha[i] = int(input()) 13 | 14 | for s in formula[0]: 15 | if s.isupper(): 16 | stack.append(alpha[ord(s) - ord('A')]) 17 | else: 18 | n2 = stack.pop() 19 | n1 = stack.pop() 20 | if s == '+': 21 | stack.append(n1+n2) 22 | elif s == '-': 23 | stack.append(n1-n2) 24 | elif s == '*': 25 | stack.append(n1*n2) 26 | elif s == '/': 27 | stack.append(n1/n2) 28 | print(format(stack[0], ".2f")) 29 | 30 | -------------------------------------------------------------------------------- /한석희/RemoveDuplicatesfromSortedList/solution1.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func deleteDuplicates(_ head: ListNode?) -> ListNode? { 3 | 4 | // 0,1 개면 바로 리턴 5 | if (head == nil || head?.next == nil){ 6 | return head 7 | } 8 | 9 | // 2개 이상의 노드있다. 10 | var stack : [Int] = [] 11 | var lastValue : Int? = nil 12 | var node = head 13 | 14 | // stack 완성시키기 15 | while node != nil { 16 | // 첫 입력 17 | if lastValue == nil { 18 | stack.append( node!.val ) 19 | lastValue = node!.val 20 | node = node?.next 21 | continue 22 | }else{ 23 | // lastValue와 새로운 노드 값이 다를 경우 24 | if node!.val != lastValue! { 25 | stack.append( node!.val ) 26 | lastValue = node!.val 27 | node = node?.next 28 | continue 29 | }else{ 30 | // lastValue와 새로운 노드 값이 같았다. 31 | if let topValue = stack.last{ 32 | if topValue == node!.val { 33 | // lastValue, topValue와 같을 경우 34 | stack.popLast() 35 | node = node?.next 36 | continue 37 | }else{ 38 | // lastValue와 같으나, topValue와 다들 경우 39 | node = node?.next 40 | continue 41 | } 42 | }else{ 43 | // lastValue와 같으나, 이미 탑 발류가 팝되었고, 스택이 비었을 경우 44 | node = node?.next 45 | continue 46 | } 47 | } 48 | } 49 | } 50 | 51 | // 스택이 비어버린 경우 52 | if stack.isEmpty { 53 | return nil 54 | } 55 | 56 | // 스택에 한 개 이상 남은 경우 57 | // 스택 58 | var head : ListNode? = ListNode( stack.removeFirst() ) 59 | var node1 : ListNode? = head 60 | for val in stack { 61 | var newNode : ListNode? = ListNode( stack.removeFirst() ) 62 | node1?.next = newNode 63 | node1 = node1?.next 64 | } 65 | 66 | return head 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /한석희/RotateList/solution-3.swift: -------------------------------------------------------------------------------- 1 | // solution3.0 2 | // speed upper 98% 3 | // memory upper 10% 4 | 5 | class Solution { 6 | 7 | func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? { 8 | 9 | // 기존에 소거할 케이스들 리턴 - 길이 0, 1 10 | guard !( head == nil || head?.next == nil )else{ 11 | return head 12 | } 13 | // 14 | var tail : ListNode? 15 | var node = head 16 | var count = 0 17 | while node != nil { 18 | tail = node 19 | node = node!.next 20 | count += 1 21 | } 22 | // 23 | var k = k % count 24 | if k == 0 { return head } 25 | // head 이동 칸 수 26 | var slice = count - k 27 | 28 | // 29 | var prev : ListNode? 30 | node = head 31 | while slice > 0 { 32 | prev = node 33 | node = node!.next 34 | slice -= 1 35 | } 36 | 37 | prev!.next = nil 38 | tail!.next = head 39 | return node 40 | 41 | }// func 42 | }// class 43 | -------------------------------------------------------------------------------- /한석희/xDivide/solution.swift: -------------------------------------------------------------------------------- 1 | 2 | func divide(list: LinkedList, by value: Int) { 3 | 4 | var xNode = Node(value: value) 5 | var newHead : Node? = xNode 6 | var newTail : Node? = xNode 7 | 8 | // 9 | var node = list.head 10 | 11 | while let nowNode = node { 12 | 13 | if nowNode.value > value { 14 | 15 | newTail?.next = Node(value: nowNode.value) 16 | newTail = newTail?.next 17 | 18 | } 19 | else if nowNode.value < value { 20 | 21 | let newNode = Node(value: nowNode.value) 22 | newNode.next = newHead 23 | newHead = nowNode 24 | 25 | } 26 | else { 27 | let newNode = Node(value: value, next: nowNode.next) 28 | nowNode.next = newNode 29 | } // 30 | 31 | node = node?.next 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /한석희/큐_하노이탑/solution.swift: -------------------------------------------------------------------------------- 1 | 2 | class Tower { 3 | 4 | public var disks : [Int] 5 | private var index : Int 6 | 7 | public init(index : Int){ 8 | 9 | self.disks = [] 10 | self.index = index 11 | 12 | } 13 | 14 | public func towerIndex() -> Int { 15 | return self.index 16 | } 17 | 18 | public func add(newDisk : Int){ 19 | 20 | if !disks.isEmpty && disks.last! <= newDisk { 21 | fatalError("Error placing disk to tower : \(self.index)") 22 | } 23 | else{ 24 | disks.append(newDisk) 25 | } 26 | 27 | } 28 | 29 | // 30 | public func moveTopTo(t : Tower){ 31 | if let top = disks.popLast() { 32 | t.add(newDisk: top) 33 | } 34 | } 35 | 36 | // 37 | public func moveDisks(n : Int, destination : Tower, buffer : Tower){ 38 | if n > 0 { 39 | moveDisks(n: n - 1, destination: buffer, buffer: destination) 40 | moveTopTo(t: destination) 41 | buffer.moveDisks(n: n - 1 , destination: destination, buffer: self) 42 | } 43 | } 44 | 45 | } 46 | 47 | // put how many disks in total 48 | let n = 3 49 | var towers : [Tower] = [] 50 | for i in (0...2){ 51 | towers.append( Tower(index: i) ) 52 | } 53 | for k in (0...2){ 54 | var i = k 55 | i = 3 - i 56 | towers[0].add(newDisk: i) 57 | } 58 | towers[0].moveDisks( n: n, destination: towers[2], buffer: towers[1] ) 59 | towers[2].disks 60 | 61 | -------------------------------------------------------------------------------- /한석희/쇠막대기/solution.py: -------------------------------------------------------------------------------- 1 | def solution(arrangement): 2 | # 3 | answer = 0 4 | stack = [] 5 | 6 | # 7 | i = 0 8 | while i < len(arrangement) : 9 | 10 | char = arrangement[i] 11 | 12 | # "(" -> ) 13 | if char == "(" and arrangement[i+1] == ")" : 14 | answer += len(stack) 15 | # "(" -> ( 16 | elif char == "(" and arrangement[i+1] == "(" : 17 | stack.append("(") 18 | # ) -> ")" 19 | elif char == ")" and arrangement[i-1] == ")" : 20 | stack.pop() 21 | answer += 1 22 | # ) -> "(" 23 | elif char == ")" and arrangement[i-1] == "(" : 24 | i += 1 25 | continue 26 | 27 | # 28 | i += 1 29 | 30 | # 31 | return answer 32 | -------------------------------------------------------------------------------- /한석희/주식가격/solution_1차_시도.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def solution(prices): 4 | 5 | # 1. ind, val stack (array) 6 | indexValueStack = [] 7 | # 2. lastedTimeStack (array) 8 | lastedTimeStack = np.array( [] ) 9 | # 3. 결과 튜플 10 | resultTuplesArray = [] 11 | 12 | # 프라이스 이터레이션 13 | for index, price in enumerate(prices) : 14 | 15 | # 처음이면 그냥 넣기 16 | if not indexValueStack : 17 | indexValueStack.append( [index, price] ) 18 | lastedTimeStack = np.append(lastedTimeStack, 0) 19 | continue 20 | 21 | # 요소가 있었으면 탑 요소 피크 22 | topElement = indexValueStack[-1][1] 23 | # 새로운 요소 < 탑 요소 24 | if topElement > price : 25 | 26 | while topElement > price : 27 | 28 | # pop two stack => merge and append to result 29 | topElement = indexValueStack.pop() 30 | topLastedTime = lastedTimeStack[-1] + 1 # 가설 : 넘파이 덧셈이 O(1)이 아닌 경우 31 | lastedTimeStack = lastedTimeStack[:-1] 32 | 33 | # append to result 34 | resultTuplesArray.append( ( topElement[0], topElement[1], topLastedTime ) ) 35 | 36 | # if it's already empty - don't need to go out 37 | if not indexValueStack : 38 | break 39 | 40 | # for next element try !! 41 | topElement = indexValueStack[-1][1] 42 | 43 | # 이후 남아있는 lastedTimestack numpy + 1 해준다. 44 | lastedTimeStack = np.add( lastedTimeStack, np.ones( len(lastedTimeStack) ) ) 45 | 46 | # 새로운 요소의 (인덱스, 값)을 1에 푸쉬, 2에 0 푸쉬 해준다. 47 | indexValueStack.append( [index, price] ) 48 | lastedTimeStack = np.append(lastedTimeStack, 0) 49 | 50 | # 새로운 요소가 탑 요소보다 크거나 같을 때 51 | else : 52 | # 2에 +1을 해준후 53 | lastedTimeStack = np.add( lastedTimeStack, np.ones( len(lastedTimeStack) ) ) 54 | # 새로운 요소 (인덱스, 값)을 1에 푸쉬 새로운 요소를 위한 0 푸쉬 55 | indexValueStack.append( [index, price] ) 56 | lastedTimeStack = np.append(lastedTimeStack, 0) 57 | 58 | # 이터레이션 끝 59 | 60 | # 스택에 남아있는 것을 튜플로 합쳐서 결과 튜플로 가져오기 !! 61 | for i in range( len(indexValueStack) ): 62 | resultTuplesArray.append( ( indexValueStack[i][0], indexValueStack[i][1], lastedTimeStack[i] ) ) 63 | # 결과를 인덱스 기준으로 오름차순 정렬 64 | resultTuplesArray = sorted( resultTuplesArray, key=lambda x: x[0], reverse=False) 65 | # 떨어지지 않은 지속 시간만 남긴다. 66 | answer = [ int(i[2]) for i in resultTuplesArray ] 67 | 68 | return answer 69 | 70 | 71 | # 이터레이션을 한 번만 하기 위해, 스택을 두 개로 분리하였고, 72 | # <뇌피셜>이지만 넘파이 벡터합이 O(1)이라고 생각하여, 73 | # 위와 같이 진행하였으나 시간을 초과하였습니다. 74 | 75 | # 1). 마지막 정렬이 O(N * Log N)이어서, 이 알고리즘은 O(n * log n)이 될 줄 알았는데, 시간 초과로 뜨네요? 76 | # 2). numpy.add가 O(1)이 아닌걸까요? 77 | # 도와주세요 !! ^^ 78 | -------------------------------------------------------------------------------- /한석희/주식가격/solution_2차_시도.py: -------------------------------------------------------------------------------- 1 | def solution(prices): 2 | # 3 | entryNum = len(prices) 4 | # 5 | answer = [0] * entryNum 6 | # 7 | for i in range( entryNum ) : 8 | for j in range(i+1, entryNum) : 9 | if prices[i] <= prices[j] : 10 | answer[i] += 1 11 | else : 12 | answer[i] += 1 13 | break 14 | # 15 | return answer 16 | 17 | 18 | # Q : 주가가 계속해서 상승하고, 데이터 갯수가 10^5개인 경우, 각 i에 대하여, 각각 n-1번, n-2번, n-3번, .... 1번 이터레이션이 필요합니다. 이 경우, 데이터 갯수가 n이라고 할 때, n(n+1)/2 - n -> 결과적으 19 | # O(n^2)가 되는데, 여전히 효율성 테스트를 통과하긴 하네요. 왜 그런 걸까요? 20 | -------------------------------------------------------------------------------- /한석희/주식가격/solution_3차_시도.py: -------------------------------------------------------------------------------- 1 | # O(n) 시간 복잡도 - cpp 프로그래머스 참고 2 | def solution(prices): 3 | 4 | # price의 사이즈 재기 5 | size = len(prices) 6 | # price의 길이에 맞게 answer만들기 7 | answer = [0] * size 8 | # 스택 리스트 만들기 9 | stack = [] 10 | 11 | # 프라이스 이터레이션 시작 12 | for i in range(size) : 13 | # 스택이 비어있지 않고, 새로들어온 주가에 비해, 스택 맨 위의 주가가 "높다면" 14 | while (stack) and ( stack[ -1 ] > prices[ i ] ) : 15 | poppedIndex = stack.pop() 16 | answer[ poppedIndex ] = i - poppedIndex 17 | # 새로운 요소(인덱스)를 스택에 넣는다. 18 | stack.append( i ) 19 | 20 | # 스택에 남은 거 떨기 21 | while stack : 22 | # 스택 하나하나 마다 23 | poppedIndex = stack.pop() 24 | # 프라이스의 사이즈 - 1에서 그 값 뺀 값을 25 | answer[ poppedIndex ] = ( ( size - 1 ) - poppedIndex ) 26 | 27 | return answer 28 | -------------------------------------------------------------------------------- /한석희/큐_DesignCircularDeque/solution.swift: -------------------------------------------------------------------------------- 1 | class MyCircularQueue { 2 | 3 | var readIndex = 0 4 | var writeIndex = 0 5 | var ringSize : Int 6 | var baseArray : Array = [ ] 7 | 8 | /** Initialize your data structure here. Set the size of the queue to be k. */ 9 | init(_ k: Int) { 10 | ringSize = k 11 | baseArray = Array(repeating: nil, count: ringSize) 12 | } 13 | 14 | /** Insert an element into the circular queue. Return true if the operation is successful. */ 15 | func enQueue(_ value: Int) -> Bool { 16 | 17 | guard !isFull() else {return false} 18 | 19 | baseArray[ writeIndex % ringSize ] = value 20 | writeIndex += 1 21 | 22 | return true 23 | 24 | } 25 | 26 | /** Delete an element from the circular queue. Return true if the operation is successful. */ 27 | func deQueue() -> Bool { 28 | 29 | guard !isEmpty() else { 30 | return false 31 | } 32 | 33 | readIndex += 1 34 | return true 35 | 36 | } 37 | 38 | /** Get the front item from the queue. */ 39 | func Front() -> Int { 40 | 41 | if isEmpty(){ 42 | return -1 43 | } 44 | 45 | return baseArray[ readIndex % ringSize ]! 46 | } 47 | 48 | /** Get the last item from the queue. */ 49 | func Rear() -> Int { 50 | 51 | // no ele 52 | if isEmpty(){ 53 | return -1 54 | } 55 | 56 | // 57 | return baseArray[ ( (writeIndex-1) % ringSize ) ]! 58 | } 59 | 60 | /** Checks whether the circular queue is empty or not. */ 61 | func isEmpty() -> Bool { 62 | 63 | if writeIndex - readIndex == 0 { 64 | return true 65 | } 66 | 67 | return false 68 | 69 | } 70 | 71 | /** Checks whether the circular queue is full or not. */ 72 | func isFull() -> Bool { 73 | 74 | if ( (( writeIndex - readIndex ) == ringSize) && (writeIndex != 0) ) { 75 | return true 76 | } 77 | 78 | return false 79 | } 80 | 81 | } 82 | 83 | /** 84 | * Your MyCircularQueue object will be instantiated and called as such: 85 | * let obj = MyCircularQueue(k) 86 | * let ret_1: Bool = obj.enQueue(value) 87 | * let ret_2: Bool = obj.deQueue() 88 | * let ret_3: Int = obj.Front() 89 | * let ret_4: Int = obj.Rear() 90 | * let ret_5: Bool = obj.isEmpty() 91 | * let ret_6: Bool = obj.isFull() 92 | */ 93 | -------------------------------------------------------------------------------- /한석희/큐_MaxSumOfRect/solution.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxSumSubmatrix(_ matrix: [[Int]], _ k: Int) -> Int { 3 | 4 | 5 | let rowNum = 0...(matrix.count - 1) // row indices 6 | let colNum = 0...(matrix[0].count - 1) // col indices 7 | 8 | // two rows combinations 9 | var rowCombs : [ (Int, Int) ] = [] 10 | for i in rowNum { 11 | for j in rowNum where j >= i { 12 | rowCombs.append( (i, j) ) 13 | } 14 | } 15 | 16 | // two columns combinations 17 | var colCombs : [ (Int, Int) ] = [] 18 | for i in colNum { 19 | for j in colNum where j >= i { 20 | colCombs.append( (i, j) ) 21 | } 22 | } 23 | 24 | // with different set of rowCombs & colCombs 25 | // 1). find four points sums 26 | // 2). and append 27 | var possibleSums = [ Int ]() 28 | 29 | // for given matrix => get all possible rectangle sums 30 | for aRowComb in rowCombs { 31 | for aColComb in colCombs { 32 | 33 | if aRowComb.0 != aRowComb.1 && 34 | aColComb.0 != aColComb.1 { 35 | var aSum = 0 36 | for i in (aRowComb.0 ... aRowComb.1){ 37 | for j in (aColComb.0...aColComb.1){ 38 | aSum += matrix[i][j] 39 | } 40 | } 41 | possibleSums.append(aSum) 42 | } 43 | 44 | else if aRowComb.0 == aRowComb.1 && 45 | aColComb.0 != aColComb.1 { 46 | var aSum = 0 47 | let rowIndex = aRowComb.0 48 | for i in (aColComb.0...aColComb.1){ 49 | aSum += matrix[rowIndex][i] 50 | } 51 | possibleSums.append(aSum) 52 | } 53 | 54 | else if aRowComb.0 != aRowComb.1 && 55 | aColComb.0 == aColComb.1 { 56 | var aSum = 0 57 | let colIndex = aColComb.0 58 | for i in (aRowComb.0...aRowComb.1){ 59 | aSum += matrix[i][colIndex] 60 | } 61 | possibleSums.append(aSum) 62 | } 63 | else if aRowComb.0 == aRowComb.1 && 64 | aColComb.0 == aColComb.1 { 65 | possibleSums.append( matrix[aRowComb.0][aColComb.0] ) 66 | } 67 | 68 | } 69 | 70 | } 71 | 72 | 73 | return possibleSums.filter{ $0 <= k }.max()! 74 | } 75 | 76 | } 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /한석희/큐_하노이탑/solution.swift: -------------------------------------------------------------------------------- 1 | 2 | class Tower { 3 | 4 | public var disks : [Int] 5 | private var index : Int 6 | 7 | public init(index : Int){ 8 | 9 | self.disks = [] 10 | self.index = index 11 | 12 | } 13 | 14 | public func towerIndex() -> Int { 15 | return self.index 16 | } 17 | 18 | public func add(newDisk : Int){ 19 | 20 | if !disks.isEmpty && disks.last! <= newDisk { 21 | fatalError("Error placing disk to tower : \(self.index)") 22 | } 23 | else{ 24 | disks.append(newDisk) 25 | } 26 | 27 | } 28 | 29 | // 30 | public func moveTopTo(t : Tower){ 31 | if let top = disks.popLast() { 32 | t.add(newDisk: top) 33 | } 34 | } 35 | 36 | // 37 | public func moveDisks(n : Int, destination : Tower, buffer : Tower){ 38 | if n > 0 { 39 | moveDisks(n: n - 1, destination: buffer, buffer: destination) 40 | moveTopTo(t: destination) 41 | buffer.moveDisks(n: n - 1 , destination: destination, buffer: self) 42 | } 43 | } 44 | 45 | } 46 | 47 | // put how many disks in total 48 | let n = 3 49 | var towers : [Tower] = [] 50 | for i in (0...2){ 51 | towers.append( Tower(index: i) ) 52 | } 53 | for k in (0...2){ 54 | var i = k 55 | i = 3 - i 56 | towers[0].add(newDisk: i) 57 | } 58 | towers[0].moveDisks( n: n, destination: towers[2], buffer: towers[1] ) 59 | towers[2].disks 60 | 61 | --------------------------------------------------------------------------------