力扣-1678. 设计 Goal 解析器

本文最后更新于:2022年11月6日 晚上

题目描述

1678

思路和实现

直接调用函数

这题不偷懒那还是人吗?直接上replace()好吧!

1
2
3
class Solution:
def interpret(self, command: str) -> str:
return command.replace("()", "o").replace("(al)", "al")

正经遍历

OK,偷懒偷完了还是要回归本心的,可以直接遍历,然后通过一些if判断怎么转换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def interpret(self, command: str) -> str:
str_len = len(command)
i = 0
result = ""
while i < str_len:
if command[i] == 'G': # 遇到G,直接写到结果里
result += "G"
i += 1
elif command[i] == '(': # 遇到左括号,看跟在后面的字符分情况讨论
if command[i + 1] == 'a': # 后边跟的是 a
result += "al"
i += 4
else: # 后边跟的是 (
result += "o"
i += 2
return result

这里有一只爱丽丝

希望本文章能够帮到您~


力扣-1678. 设计 Goal 解析器
https://map1e-g.github.io/2022/11/06/leetcode-1678/
作者
MaP1e-G
发布于
2022年11月6日
许可协议