LeetCode简单题之设计 Goal 解析器
生活随笔
收集整理的這篇文章主要介紹了
LeetCode简单题之设计 Goal 解析器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
請你設計一個可以解釋字符串 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)” 按某種順序組成
來源:力扣(LeetCode)
解題思路
??這類題比較簡單只需要按照規則查驗字符是否符合某條規則即可。
class Solution:def interpret(self, command: str) -> str:i=0temp=''while i<len(command):if command[i]=='G':temp+='G'i+=1elif command[i]=='(' and command[i+1]==')':temp+='o'i+=2else:temp+='al'i+=4return temp
class Solution:def interpret(self, command: str) -> str:def change(match):char=match.group('char')if len(char)==1:return 'G'elif len(char)==2:return 'o'else:return 'al'return re.sub('(?P<char>G|\(\)|\(al\))',change,command)
總結
以上是生活随笔為你收集整理的LeetCode简单题之设计 Goal 解析器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode简单题之生成每种字符都是
- 下一篇: LeetCode简单题之判断国际象棋棋盘