문자열의 순열
'문자열의 순열' 문제에 대한 자세한 가이드 및 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
생산 표준에 맞게 코드를 정리합니다.
문제 설명
두 개의 문자열 s1 및 s2이 주어지면 s2에 s1의 순열이 포함되어 있으면 True를 반환하고 그렇지 않으면 False을 반환합니다.
즉, s1의 순열 중 하나가 s2의 하위 문자열인 경우 True을 반환합니다.
checkInclusion(s1: str, s2: str) -> bool 함수를 작성하세요.
- •1 <= len(s1), len(s2) <= 10^4
- •s1 and s2 consist of lowercase English letters
예
s1 = "ab", s2 = "eidbaooo"
True
s2 contains one permutation of s1: "ba" (starting at index 3).
s1 = "ab", s2 = "eidboaoo"
False
No permutation of "ab" exists as a contiguous substring in s2.
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 check_inclusion_opt(s1, s2):
if len(s1) > len(s2): return False
s1Count, s2Count = [0] * 26, [0] * 26
for i in range(len(s1)):
s1Count[ord(s1[i]) - ord('a')] += 1
s2Count[ord(s2[i]) - ord('a')] += 1
matches = 0
for i in range(26):
if s1Count[i] == s2Count[i]: matches += 1
l = 0
for r in range(len(s1), len(s2)):
if matches == 26: return True
index = ord(s2[r]) - ord('a')
s2Count[index] += 1
if s1Count[index] == s2Count[index]: matches += 1
elif s1Count[index] + 1 == s2Count[index]: matches -= 1
index = ord(s2[l]) - ord('a')
s2Count[index] -= 1
if s1Count[index] == s2Count[index]: matches += 1
elif s1Count[index] - 1 == s2Count[index]: matches -= 1
l += 1
return matches == 26무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
def check_inclusion_brute(s1, s2):
n1, n2 = len(s1), len(s2)
if n1 > n2: return False
s1_sorted = sorted(s1)
for i in range(n2 - n1 + 1):
if sorted(s2[i : i + n1]) == s1_sorted:
return True
return FalseAlgorithm 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 Try/Except 및 오류 처리
Python 스크립트가 충돌하는 것을 방지하세요. try, Except, finally 블록과 사용자 정의 예외를 올바르게 발생시키는 방법을 알아보세요.
Python에서 문자열을 뒤집는 방법
슬라이싱, reversed() 함수, 루프 연결을 사용하여 Python에서 문자열을 반전하는 방법을 시각적 코드 예제와 함께 알아보세요.
Python 문자열 메서드 치트 시트
Python 문자열 조작에 대한 완전한 참조 가이드입니다. 문자열 속성의 서식 지정, 검색, 분할, 바꾸기 및 확인을 마스터합니다.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.