โจทย์
Goal Parser แปลคำสั่ง:
G→G()→o(al)→al
ตัวอย่าง: command = "G()()()(al)(al)" → Output: "Goooalal"
อัลกอริธึม
- วนอ่านตัวอักษร
- ถ้า
G→ เพิ่มG - ถ้า
(ตามด้วย)→ เพิ่มo - ถ้า
(al)→ เพิ่มal(ข้ามวงเล็บ)
โค้ด Python
def solve(command):
s = ""
i = 0
while i < len(command):
if command[i] == 'G':
s += 'G'
i += 1
elif command[i] == '(':
if i + 1 < len(command) and command[i+1] == ')':
s += 'o'
i += 2
else: # (al)
s += 'al'
i += 4
else:
i += 1
return s
command = "G()()()(al)(al)"
print(solve(command)) # Output: Goooalal
Input / Output
Input: "G()()()(al)(al)"
Output: Goooalal