在 Python 中查找目标解析器解释命令的程序

pythonserver side programmingprogramming更新于 2025/5/1 13:00:17

假设我们有一个可以解释给定字符串命令的目标解析器。命令由以下部分组成:

  • 字母表"G",

  • 左括号和右括号"()"

  • 和/或"(al)"按某种顺序排列。

我们的目标解析器将把"G"解释为字符串"G",将"()"解释为"o",将"(al)"解释为字符串"al"。最后,将解释后的字符串按原始顺序连接起来。因此,如果我们有字符串命令,我们必须找到目标解析器对命令的解释。

因此,如果输入类似于命令 = "G()()()(al)(al)",则输出将是 Goooalal。

为了解决这个问题,我们将遵循以下步骤 −

  • s:= 空字符串

  • 对于范围为 0 到命令大小 - 1 的 i,执行

    • 如果命令 [i] 与 "(" 不同且命令 [i] 与 ")" 不同,则

      • s := s 连接命令 [i]

    • 如果命令 [i] 与"(" 并且 command[i+1] 与 ")" 和 i+1<len(command) 相同,则

      • s := s 连接 'o'

    • 如果 command[i] 与 "(" 相同,则

      • 进行下一次迭代

    • 如果 command[i] 与 ")" 相同,则

      • 进行下一次迭代

  • 返回 s

示例 (Python)

让我们看看下面的实现以便更好地理解 −

def solve(command):
   s=""
   for i in range(len(command)):
      if command[i]!="(" and command[i]!=")":
         s+=command[i]
      if command[i]=="(" and command[i+1]==")" and i+1<len(command):
         s+='o'
      if command[i]=="(":
         continue
      if command[i]==")":
         continue
   return s

command = "G()()()(al)(al)"
print(solve(command))

输入

"G()()()(al)(al)"

输出

Goooalal

相关文章


有用资源