请你设计一个可以解释字符串 command
的 Goal 解析器 。command
由 "G"
、"()"
和/或 "(al)"
按某种顺序组成。Goal 解析器会将 "G"
解释为字符串 "G"
、"()"
解释为字符串 "o"
,"(al)"
解释为字符串 "al"
。然后,按原顺序将经解释得到的字符串连接成一个字符串。给你字符串 command
,返回 Goal 解析器 对 command
的解释结果。
示例 1:
输入:command = "G()(al)" 输出:"Goal" 解释:Goal 解析器解释命令的步骤如下所示: G -> G () -> o (al) -> al 最后连接得到的结果是 "Goal"
字符串替换:
根据题意,只需要将字符串 command
中的 "()"
替换为 'o'
,"(al)"
替换为 "al"
即可。
class Solution:
def interpret(self, command: str) -> str:
return command.replace('()','o').replace('(al)', 'al')
字符串遍历:
也可以对字符串command进行遍历,对其中的每个字符c:如果是'G'直接加到结果串res中,如果是'(',判断下一个是不是')',若是,将'o'加到结果串中,若不是,将'al'返回到结果串中。
class Solution:
def interpret(self, command: str) -> str:
res = []
for i,c in enumerate(command):
if c == 'G':
res.append(c)
elif c == '(':
res.append('o' if command[i+1]==')' else 'al')
return ''.join(res)