持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情
一、题目描述:
1678. 设计 Goal 解析器 - 力扣(LeetCode)
请你设计一个可以解释字符串 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"
示例 2:
输入:command = "G()()()()(al)"
输出:"Gooooal"
示例 3:
输入:command = "(al)G(al)()()G"
输出:"alGalooG"
提示:
- 1 <= command.length <= 100
- command 由 "G"、"()" 和/或 "(al)" 按某种顺序组成
二、思路分析:
按长度去跳index,如果i是G,就用list存一个G,如果i是(,就看i到i+1是否(),i到i+3是否是(al),同时控制跳跃步数,在最后去更新index
注意:
最后把list转为str就可以:''.join(has)
list切片的取值方式是左闭右开区间。
三、AC 代码:
class Solution:
def interpret(self, command: str) -> str:
#按长度去跳index,如果i是G,就存一个G,如果i是(,就看i到i+1是否(),i到i+3是否是(al),同时控制跳跃步数,在最后去更新index
index = 0
command = list(command)
has = []
while(index<len(command)):
if command[index] =='G':
has.append('G')
step = 1
if command[index] =='(':
if "()" == ''.join(command[index:index+2]):
has.append('o')
step = 2
if "(al)" == ''.join(command[index:index+4]):
has.append('al')
step = 4
index = index+step
return ''.join(has)
四、总结:
其他的其实还有不少的解法,比如正则,比如状态机,还有很多优化的空间
五、参考: