【代码编辑器】Python 实现

360影视 国产动漫 2025-04-30 09:52 2

摘要:def text_editor:K = int(input)text = input.stripcommands = [input.strip for _ in range(K)]pos = 0 # 初始指针位置for cmd in commands:part

def text_editor:K = int(input)text = input.stripcommands = [input.strip for _ in range(K)]pos = 0 # 初始指针位置for cmd in commands:parts = cmd.splitif not parts:continueop = 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 = idxelif op == 'SEARCH-BACKWARD':word = ' '.join(parts[1:])idx = text.rfind(word, 0, pos)if idx != -1:pos = idxelif op == 'INSERT':word = ' '.join(parts[1:])text = text[:pos] + word + text[pos:]pos += len(word)elif op == 'REPLACE':word = ' '.join(parts[1:])if pos

解决思路

第一行是命令的数量K。第二行是原始文本。

接下来的K行是具体的指令。

初始指针位置为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、​输出结果​:

处理完所有指令后,输出最终文本。

来源:小媛谈科技

相关推荐