Cho chuỗi s chỉ chứa 'X', '(', ')' với ngoặc cân bằng. Đếm số ký tự 'X' tại mỗi độ sâu ngoặc, từ sâu nhất đến sâu nhất.
Ví dụ: s="(XXX(X(XX))XX)" → [5, 1, 2].
Giải thuật (Duyệt một lần)
- Khởi tạo
depth = -1, mảng kết quảout = [] - Duyệt từng ký tự:
'(': tăngdepth')': giảmdepth- Nếu
depth == len(out): thêm 0 vàoout 'X': tăngout[depth]
Ví dụ triển khai
def solve(s):
depth = -1
out = []
for c in s:
if c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth == len(out):
out.append(0)
if c == "X":
out[depth] += 1
return out
print(solve("(XXX(X(XX))XX)"))
Đầu vào
"(XXX(X(XX))XX)"
Đầu ra
[5, 1, 2]