728x90

python 53

[Leetcode / Python] 1415. The k-th Lexicographical String of All Happy Strings of Length n

난이도 : medium a, b, c로만 구성되어있고 'aa'나 'bb'처럼 동일한 알파벳이 반복되지 않는, 길이가 n인 happy string의 k번째 갯수를 return하는 문제 class Solution: def getHappyString(self, n: int, k: int) -> str: let = ['a', 'b', 'c'] for _ in range(1, n): new = [] for prev in let: for char in 'abc': if prev[-1] != char: new.append(prev + char) ..

[Leetcode / Python] 2375. Construct Smallest Number From DI String

난이도 : medium 길이가 n인 문자열 pattern에서 I는 증가하는 것, D는 감소하는 것을 의미길이가 n+1인 숫자 num은, 1부터 9까지의 숫자에서 하나씩만 사용하며, num[i]와 num[i+1] 사이에 다음과 같은 규칙을 만족할 때, num의 최소값을 구하는 문제 class Solution: def smallestNumber(self, pattern: str) -> str: n = len(pattern) result = [] a = list(range(1, 10)) for i in range(n + 1): if i == n or pattern[i] == 'I': result.ap..

[Leetcode / Python] 3066. Minimum Operations to Exceed Threshold Value II

난이도 : medium 리스트 nums와 숫자 k가 있을때,nums에서 가장 작은 두 개의 숫자 x, y를 nums에서 제거하고, min(x, y)*2 + max(x, y)를 리스트에 넣는 계산을 반복nums의 요소가 전부 k보다 클때까지 계산을 진행하는 횟수를 return하는 문제 import heapqclass Solution: def minOperations(self, nums: List[int], k: int) -> int: heapq.heapify(nums) i = 0 while nums[0] heapq를 가져오고, 리스트를 heapify한다. (heap 자료구조는 priority quere)nums[0] (최소값)이 k보다 작을 때까지 ..

[Leetcode / Python] 2364. Count Number of Bad Pairs

난이도 : medium 리스트 nums에서 (j > i) num[j] -num[i] != j - i인 쌍을 찾는 문제 리스트 nums에서 2개의 요소로 이루어진 total 수에서 num[j] -num[i] = j - i 인 쌍을 빼면 될 것.num[j] - j = num[i] - i = a라고 해석할 수 있는데,이 a값으로만 이루어진 요소가 몇 개인지 count 후 count * (count -1 ) / 2를 취한 값을 sum하면 풀린다.from collections import Counterclass Solution: def countBadPairs(self, nums: List[int]) -> int: n = len(nums) total = n * (n - 1)// 2 ..

[Leetcode / Python] 3174. Clear Digits

난이도 : easy 문자열 내에 숫자가 있다면, 숫자 및 숫자에 가장 가까운 왼쪽 문자열(숫자 아님) 하나를 같이 지우는 문제 import reclass Solution: def clearDigits(self, s: str) -> str: while re.findall(r'\d',s): s = re.sub(r'\D\d', '', s) return sre를 import 후, re.findall로 s에 숫자가 있는지 확인re.sub으로 \D(숫자가 아닌 것) \d(숫자)를 지우기Runtime : 4ms (10.63%)Memory : 17.84MB (27.74%)

[Leetcode / Python] 1910. Remove All Occurrences of a Substring

난이도 : medium 문자열 s의 part 문자열을 왼쪽 부터 하나씩 제거하는 문제. 맨 처음에는 그냥 import re 및 re.sub을 통해서 제거했으나, 한번에 제거하는 문제가 아니었다.class Solution: def removeOccurrences(self, s: str, part: str) -> str: while part in s: s = s.replace(part, "", 1) return sreplace로 part를 빈 문자열로 바꾸고, 왼쪽부터 하나만 바꾼다는 while문으로 해결 Runtime : 0msMemory :  17.94MB

[Python] 142. Linked List Cycle II

난이도 : medium linked list의 cycle이 시작하는 지점을 return하는 문제.cycle이 없으면 null return 보통 linked list에서 cycle에 관련된 문제는, Floyd's Tortoise and Hare 알고리즘을 사용하여 cycle이 있는지 확인한다.class Solution: def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = head fast = head while fast and fast.next: #Floyd's Tortoise and Hare 알고리즘 slow = slow.next ..

[Python] 1726. Tuple with Same Product

난이도 : medium a * b = c * d일 때의 tuple (a,b,c,d)의 갯수를 return하는 문제. a * b = c * d = m인 쌍의 갯수 n을 알아내고, m마다 nP2(= n * n - 1)을 취한 뒤 sum조합에서 a, b와 c, d 각각 위치를 바꿀 수 있고, (a, b)쌍과 (c, d)쌍의 위치도 바꿀 수 있기 때문에, 그 경우의 수를 고려하면 sum 값에 4를 곱해야 한다.from collections import Counterclass Solution: def tupleSameProduct(self, nums: List[int]) -> int: n = len(nums) arr = [nums[i]* nums[j] for i in range(n)..

[Python] 3151. Special Array I

난이도 : easy 리스트 nums 내의 인접한 요소가 번갈아서 홀 짝 or 짝 홀과 같은 형식으로 나타나는지 확인하는 문제 홀수와 짝수가 번갈아서 나와야 한다면, 두 요소를 더하면 무조건 홀수가 나와야 True가 된다.class Solution: def isArraySpecial(self, nums: List[int]) -> bool: n = len(nums) for i in range(1, n): if (nums[i-1] + nums[i]) % 2 == 0: return False break return True인접한 두 요소를 더했을 때 짝수가 된다면, False를 return모든 요..

[Python] 1790. Check if One String Swap Can Make Strings Equal

난이도 : easy 문자열 s1과 s2이 있고, 문자열의 자리를 한 번 바꿨을 때 두 문자열이 동일하면 True를 return하는 문제.(s1과 s2가 같아도 True) class Solution: def areAlmostEqual(self, s1: str, s2: str) -> bool: diff = [(a, b) for a, b in zip(s1, s2) if a != b] return len(diff) == 0 or (len(diff) == 2 and diff[0] == diff[1][::-1])리스트 diff는 s1과 s2 요소 중 다른 것만 묶어서 정의.이 리스트의 요소가 0개이거나(s1 == s2),  리스트의 요소가 2개이며 diff[0]과 뒤집은 diff[1]..

카테고리 없음 2025.02.05
728x90