Python 實現目標解析器命令解釋程式
假設我們有一個目標解析器,可以解釋給定的字串命令。一個命令由以下組成:
字母“G”,
圓括號“()”,
和/或“(al)”以某種順序組合。
我們的目標解析器將“G”解釋為字串“G”,“()”解釋為“o”,“(al)”解釋為字串“al”。最終解釋的字串將按原始順序連線起來。因此,如果我們有字串命令,我們必須找到目標解析器對命令的解釋。
因此,如果輸入類似於 command = "G()()()(al)(al)",則輸出將為 Goooalal。
為了解決這個問題,我們將遵循以下步驟:
s := 空字串
對於 i 從 0 到 command 的大小 - 1,執行:
如果 command[i] 不等於 "(" 且 command[i] 不等於 ")",則
s := s 連線 command[i]
如果 command[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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP