이 기사에서는 아래 주어진 문제 설명에 대한 솔루션에 대해 알아볼 것입니다.
문제 설명 − 텍스트와 패턴이 주어지면 텍스트에서 패턴과 그 순열(또는 아나그램)의 모든 발생을 인쇄해야 합니다.
이제 아래 구현에서 솔루션을 관찰해 보겠습니다 -
예시
# maximum value
MAX = 300
# compare
def compare(arr1, arr2):
for i in range(MAX):
if arr1[i] != arr2[i]:
return False
return True
# search
def search(pat, txt):
M = len(pat)
N = len(txt)
# countP pattern account
# countTW text window count
countP = [0]*MAX
countTW = [0]*MAX
for i in range(M):
(countP[ord(pat[i]) ]) += 1
(countTW[ord(txt[i]) ]) += 1
# Traversal
for i in range(M, N):
# Compare current window and patten counts
if compare(countP, countTW):
print("Found at Index", (i-M))
# Add charcter to window
(countTW[ ord(txt[i]) ]) += 1
# remove charcter from window
(countTW[ ord(txt[i-M]) ]) -= 1
# Check for the last window
if compare(countP, countTW):
print("It is Found at Index : ", N-M)
# main
txt = "TUTORIALSPOINT"
pat = "TOR"
search(pat, txt) 출력
Found at Index 2

모든 변수는 로컬 범위에서 선언되며 해당 참조는 위 그림과 같습니다.
결론
이 기사에서는 Anagram 부분 문자열 검색을 위한 Python 프로그램을 만드는 방법에 대해 배웠습니다.