Giả sử ta có Goal Parser dịch chuỗi lệnh. Lệnh bao gồm:
- Chữ cái "G"
- Ngoặc đơn mở và đóng "()"
- Và/hoặc "(al)" theo thứ tự nào đó
Parser dịch: "G" → "G", "()" → "o", "(al)" → "al". Các chuỗi dịch sau đó nối theo thứ tự gốc. Cho chuỗi command, tìm bản dịch của Goal Parser.
Ví dụ: command = "G()()()(al)(al)", kết quả là "Goooalal".
Giải thuật
s := ""- For
itừ 0 đếnlen(command) - 1:- Nếu
command[i] != "("vàcommand[i] != ")":s += command[i] - Nếu
command[i] == "("vàcommand[i+1] == ")"vài+1 < len(command):s += 'o' - Nếu
command[i] == "(": continue - Nếu
command[i] == ")": continue
- Nếu
- Trả về
s
Ví dụ (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))
Input
"G()()()(al)(al)"
Output
Goooalal