def text_editor():
K = int(input())
text = input().strip()
commands = [input().strip() for _ in range(K)]
pos = 0 # 初始指针位置
for cmd in commands:
parts = cmd.split()
if not parts:
continue
op = parts[0]
if op == 'FORWARD':
X = int(parts[1])
pos = min(pos + X, len(text))
elif op == 'BACKWARD':
X = int(parts[1])
pos = max(pos - X, 0)
elif op == 'SEARCH-FORWARD':
word = ' '.join(parts[1:])
idx = text.find(word, pos)
if idx != -1:
pos = idx
elif op == 'SEARCH-BACKWARD':
word = ' '.join(parts[1:])
idx = text.rfind(word, 0, pos)
if idx != -1:
pos = idx
elif op == 'INSERT':
word = ' '.join(parts[1:])
text = text[:pos] + word + text[pos:]
pos += len(word)
elif op == 'REPLACE':
word = ' '.join(parts[1:])
if pos < len(text):
text = text[:pos] + word + text[pos + len(word):] if pos + len(word) <= len(text) else text[:pos] + word
else:
text = text[:pos] + word
pos += len(word)
elif op == 'DELETE':
X = int(parts[1])
text = text[:pos] + text[pos + X:]
pos = min(pos, len(text))
print(text)
text_editor()
解决思路
1、输入处理:
- 第一行是命令的数量K。
- 第二行是原始文本。
接下来的K行是具体的指令。
2、指针管理:
- 初始指针位置为0(文本开头)。
- 根据指令移动指针,确保指针不越界。
3、指令处理:
- FORWARD X:指针右移X,不超过文本末尾。
- BACKWARD X:指针左移X,不超过文本开头。
- SEARCH-FORWARD word:从指针位置向前查找word,移动指针到起始位置。
- SEARCH-BACKWARD word:从指针位置向后查找word,移动指针到起始位置。
- INSERT word:在指针位置前插入word,指针移动到word末尾。
- REPLACE word:替换指针位置的字符为word(如果word长度超过原文本长度,则直接替换)。
- DELETE X:删除指针位置的X个字符。
4、输出结果:
处理完所有指令后,输出最终文本。