본문 바로가기
Tech/Coding

ROPE 자료구조: 구조와 동작 원리(Python 예제)

by redcubes 2025. 5. 24.

긴 문자열을 효율적으로 처리해야 하는 경우, 문자열의 일부를 잘라내거나 추가하거나 특정 위치에 접근할 때마다 문자열의 길이만큼 O(n) 시간이 걸린다면 큰 문제가 될 수 있다. 이를 해결하기 위해 고안된 자료구조가 ROPE이다.

ROPE의 구조: 문자열을 트리 형태로 쪼개어 표현

ROPE는 문자열을 이진 트리(Binary Tree) 형태로 저장한다. 각 노드는 다음과 같은 정보를 가진다:

  • 왼쪽 자식 (left): 문자열의 앞부분
  • 오른쪽 자식 (right): 문자열의 뒷부분
  • weight: 왼쪽 서브트리의 전체 문자열 길이
  • 리프 노드: 실제 문자열 데이터 (짧은 문자열)

구조 예시

예를 들어, 문자열 "Hello_my_name_is_Simon"을 ROPE로 표현하면 다음과 같은 구조가 된다:

출처: https://en.wikipedia.org/wiki/Rope_(data_structure)

ROPE의 주요 동작 원리

1️⃣ 인덱스 접근 (index)

인덱스 접근은 왼쪽 자식의 weight 값을 기준으로 해당 인덱스가 왼쪽/오른쪽 중 어디에 속하는지를 판단하며 트리를 따라 내려간다.

2️⃣ 문자열 삽입 (insert)

삽입은 다음과 같은 단계를 따른다:

  1. 삽입 위치 기준으로 트리를 분리 (split)
  2. 삽입할 문자열을 새로운 ROPE 노드로 생성
  3. 분리된 트리와 삽입할 트리를 병합(concatenate)

3️⃣ 문자열 삭제 (delete)

삭제는 다음과 같은 단계를 따른다:

  1. 삭제 구간의 시작점과 끝점에서 split
  2. 삭제 구간 제거
  3. 남은 부분을 concatenate

Python 코드 예제 (간단한 ROPE 구현)

class RopeNode:
    def __init__(self, s=""):
        self.left = None
        self.right = None
        self.weight = len(s)
        self.s = s

def concatenate(left, right):
    node = RopeNode()
    node.left = left
    node.right = right
    node.weight = left.weight if left else 0
    return node

def index(node, i):
    if node is None:
        return ''
    if node.left is None and node.right is None:
        return node.s[i]
    if i < node.weight:
        return index(node.left, i)
    else:
        return index(node.right, i - node.weight)

def split(node, i):
    if node is None:
        return None, None
    if node.left is None and node.right is None:
        return RopeNode(node.s[:i]), RopeNode(node.s[i:])
    if i < node.weight:
        left1, right1 = split(node.left, i)
        return left1, concatenate(right1, node.right)
    else:
        left2, right2 = split(node.right, i - node.weight)
        return concatenate(node.left, left2), right2

def insert(node, i, s):
    left, right = split(node, i)
    return concatenate(concatenate(left, RopeNode(s)), right)

def delete(node, i, j):
    left, mid = split(node, i)
    mid, right = split(mid, j - i)
    return concatenate(left, right)

def report(node):
    if node is None:
        return ""
    if node.left is None and node.right is None:
        return node.s
    return report(node.left) + report(node.right)

# 사용 예시
root = RopeNode("HelloWorld")
root = insert(root, 5, "_")
print(report(root))  # Hello_World
root = delete(root, 5, 6)
print(report(root))  # HelloWorld

ROPE의 시간복잡도

  • index: O(log n)
  • insert: O(log n)
  • delete: O(log n)
  • concat: O(1)

ROPE의 장점과 단점

  • 장점: 긴 문자열을 효율적으로 처리 (부분 삽입/삭제/접근 빠름)
  • 단점: 구현이 복잡, 메모리 사용량 증가 가능성

ROPE를 적용하기 좋은 문제 유형

  • 문자열 편집기 (삽입/삭제/추출 빈번)
  • 부분 문자열 추출 (substring)
  • 버전 관리 (Undo/Redo)
  • 대용량 로그 처리

ROPE와 세그먼트 트리 비교

문제 유형 ROPE 세그먼트 트리
문자열 관리 O
숫자 관리 (합/최댓값/최솟값) O
부분 삽입/삭제/추출 O
구간 질의 (합/최댓값) O
메모리 효율 O
구현 난이도 높음 낮음

마무리

ROPE는 긴 문자열 처리에 특화된 자료구조로, 특히 부분 삽입/삭제/접근이 빈번한 문제에서 매우 강력하다. 텍스트 편집기나 대규모 문자열 데이터 처리 문제에서 ROPE를 고려할 만하다. 하지만 구현 난이도는 높으니, 필요에 따라 잘 선택해 사용하는 것이 좋다.


https://m.blog.naver.com/melon940925/222120515591

 

C++ STL:: rope

C++에 내장되어 있는 자료구조 중, 신기한 것을 알게되어 기록해둡니다. rope 자료구조는 자기 자신의 인...

blog.naver.com

https://en.wikipedia.org/wiki/Rope_(data_structure)

 

Rope (data structure) - Wikipedia

From Wikipedia, the free encyclopedia Data structure for storing strings A simple rope built on the string of "Hello_my_name_is_Simon". In computer programming, a rope, or cord, is a data structure composed of smaller strings that is used to efficiently st

en.wikipedia.org

 


5632버젼 관리 IDE7480Key Insertion

9548무제

'Tech > Coding' 카테고리의 다른 글

회문 끝말잇기  (0) 2025.06.02
SciComLove (2023)  (0) 2025.05.27
백준 18185 라면 사기 (Small)  (0) 2025.05.21
  (0) 2025.05.20
2399번-거리의 합  (0) 2025.05.15