| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- shiba
- Python Implementation
- 프로그래머스
- LeetCode
- 시바견
- t1
- Convert Sorted List to Binary Search Tree
- 파이썬
- kaggle
- Substring with Concatenation of All Words
- Regular Expression
- Python
- 운영체제
- 컴퓨터의 구조
- Python Code
- 315. Count of Smaller Numbers After Self
- 30. Substring with Concatenation of All Words
- 715. Range Module
- concurrency
- data science
- Decorator
- 109. Convert Sorted List to Binary Search Tree
- Protocol
- 밴픽
- Generator
- iterator
- Class
- 43. Multiply Strings
- DWG
- attribute
Archives
- Today
- Total
Scribbling
LeetCode: 395. Longest Substring with At Least K Repeating Characters 본문
Computer Science/Coding Test
LeetCode: 395. Longest Substring with At Least K Repeating Characters
focalpoint 2022. 1. 16. 13:49Idea: Any characters that have frequencies less than k work as a breakpoints, meaning that the substring we're looking for can't include that particular character. So, recursively look for substrings while excluding those characters. Time complexity is O(N).
from collections import Counter
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
return self.helper(s, k)
def helper(self, s, k):
if not s:
return 0
c = Counter(s)
bp = set()
for key, val in c.items():
if val < k:
bp.add(key)
if not bp:
return len(s)
ret = 0
i = 0
for j in range(len(s)):
if s[j] in bp:
ret = max(ret, self.helper(s[i:j], k))
i = j + 1
ret = max(ret, self.helper(s[i:], k))
return ret
Same idea, but more pythonic code would be as below.
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
return self.helper(s, k)
def helper(self, s, k):
if not s or len(s) < k:
return 0
c = min(set(s), key=s.count)
if s.count(c) >= k:
return len(s)
return max(self.longestSubstring(t, k) for t in s.split(c))

'Computer Science > Coding Test' 카테고리의 다른 글
| LeetCode: 27. Remove Element (0) | 2022.01.17 |
|---|---|
| LeetCode: 454. 4Sum II (0) | 2022.01.16 |
| LeetCode: 384. Shuffle an Array (0) | 2022.01.15 |
| LeetCode: 378. Kth Smallest Element in a Sorted Matrix (0) | 2022.01.14 |
| LeetCode: 341. Flatten Nested List Iterator (0) | 2022.01.13 |