互联网收集的od练习题, 记录解题过程. 因为无运行环境.暂时无法验证正确性,仅供参考 ( 这个需要编译环境调试,考试时提交多次才通过)
题目描述:
某公司为了更高效的编写代码,邀请你开发一款代码编辑器程序。
程序的输入为 已有的代码文本和指令序列,程序需输出编辑后的最终文本。指针初始位置位于文本的开头。
支持的指令(X为大于等于0的整数, word 为无空格的字符串):
FORWARD X 指针向前(右)移动X,如果指针移动位置超过了文本末尾,则将指针移动到文本末尾
BACKWARD X 指针向后(左)移动X,如果指针移动位置超过了文本开头,则将指针移动到文本开头
SEARCH-FORWARD word 从指针当前位置向前查找 word 并将指针移动到word的起始位置,如果未找到则保持不变
SEARCH-BACKWARD word 在文本中向后查我 word 并将指针移动到word的起始位置,如果未找到则保持不变
INSERT word 在指针当前位置前插入word,并将指针移动到word的结尾
REPLACE word 在指针当前位置替换并插入字符(删除原有字符,并增加新的字符)
DELETE X 在指针位置删除X个字符
输入:
输入的第一行为命令列表的长度K
输入的第二行为文件中的原始文本
接下来的K行,每行为一个指令
输出:
编辑后的最终结果
输入:
1
ello
INSERT h
输出: hello
输入:
2
hllo
FORWARD 1
INSERT e
输出: hello
自定义输入:
7
hllo
FORWARD 1
BACKWARD 1
SEARCH-FORWARD l
SEARCH-BACKWARD l
INSERT word
REPLACE word
DELETE 2
输出: hwordrd
def solution():
k = int(input())
content = input()
index = 0
cmds = []
for i in range(k):
cmds.append(input().split())
for cmd in cmds:
opt, s = cmd
if opt.startswith("FORWARD"):
index = min(index + int(s), len(content)) # 越界问题
elif opt.startswith("BACKWARD"):
index = max(0, index - int(s))
elif opt.startswith("SEARCH-FORWARD"): # 越界问题
if s in content[index:]:
index += content[index:].index(s)
elif opt.startswith("SEARCH-BACKWARD"):
if s in content[:index + 1]:
for j in range(index, -1, -1):
if s in content[j:index + 1]:
index = j
break
elif opt.startswith("INSERT"):
content = content[:index] + s + content[index:]
index += len(s)
elif opt.startswith("REPLACE"):
content = content[:index] + s + content[index + len(s):]
elif opt.startswith("DELETE"):
content = content[:index] + content[index + int(s):]
print(content)
if __name__ == '__main__':
while True:
solution()
文章讲述了如何编写一个代码编辑器程序,接受指令序列对输入文本进行操作,如移动指针、查找、插入和删除。
3886

被折叠的 条评论
为什么被折叠?



