가장 긴 반복 문자 교체
'가장 긴 반복 문자 교체' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'최장 반복 문자 교체' 문제는 슬라이딩 윈도우 섹션의 핵심 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
가장 긴 반복 문자 교체에 대한 논리 흐름 시각화.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
가장 긴 반복 문자 대체에 대한 문제 설명을 주의 깊게 읽으십시오.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
문자열 s과 정수 k이 제공됩니다. 문자열의 아무 문자나 선택하여 다른 대문자 영문자로 변경할 수 있습니다. 이 작업은 최대 k번 수행할 수 있습니다.
위 작업을 수행한 후 얻을 수 있는 동일한 문자를 포함하는 가장 긴 부분 문자열의 길이를 반환합니다.
characterReplacement(s: str, k: int) -> int 함수를 작성하세요.
- •1 <= len(s) <= 10^5
- •s consists of only uppercase English letters
- •0 <= k <= len(s)
예
s = "ABAB", k = 2
4
Replace the two 'A's with 'B's or vice versa to get "BBBB" or "AAAA". The longest substring is 4.
s = "AABABBA", k = 1
4
Replace the 'B' at index 3 with 'A' to get "AAAAABA". The longest substring of same characters starting from index 0 is "AAAA" with length 4.
Need a Hint?
Edge Cases to Watch
- 빈 입력 구조
- 단일 요소 입력
- 큰 수치 범위
해결할 준비가 되셨나요?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
인터뷰 통찰력 및 변형
복잡성 분석 분석
왜 시간인가?: Directly evaluates all possibilities.
왜 우주인가?: Uses standard local memory.
왜 시간인가?: Optimized paths reduce total operations.
왜 우주인가?: May trade memory for speed.
최적화된 솔루션 Python 코드
최적화된 솔루션 Python 코드
def character_replacement_opt(s, k):
count = {}
res = 0
l = 0
maxf = 0
for r in range(len(s)):
count[s[r]] = 1 + count.get(s[r], 0)
maxf = max(maxf, count[s[r]])
if (r - l + 1) - maxf > k:
count[s[l]] -= 1
l += 1
res = max(res, r - l + 1)
return res무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
def character_replacement_brute(s, k):
res = 0
for i in range(len(s)):
counts = {}
max_f = 0
for j in range(i, len(s)):
counts[s[j]] = 1 + counts.get(s[j], 0)
max_f = max(max_f, counts[s[j]])
if (j - i + 1) - max_f <= k:
res = max(res, j - i + 1)
return resAlgorithm Pattern Checklist
When dealing with Sliding Window data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
표준 슬라이딩 윈도우 문제 속성이 적용됩니다.
관련 질문
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
권장 Python 리소스
관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.
Python 루프
Python 루프를 사용하여 데이터를 반복하는 방법을 알아보세요. 대화형 예제를 통해 for 루프, while 루프, 중단, 계속 및 루프 모범 사례를 마스터하세요.
Python에서 문자열의 문자를 바꾸는 방법
Python 문자열에서 문자나 부분 문자열을 바꾸는 방법을 알아보세요. 교체() 메서드, 개수 제한, 여러 문자 번역 사용을 마스터하세요.
Python 문자열 메서드 치트 시트
Python 문자열 조작에 대한 완전한 참조 가이드입니다. 문자열 속성의 서식 지정, 검색, 분할, 바꾸기 및 확인을 마스터합니다.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.