Cho chuỗi mã hóa: chuỗi con lặp lại được biểu diễn bằng chuỗi con theo sau số lần lặp. Ví dụ: "pq2rs2", k=5 → giải mã "pqpqrsrs", ký tự thứ 5 là 'r'. Tần suất có thể nhiều chữ số.
Ví dụ: "pq4r2ts3", k=11 → Kết quả: 't' (giải mã: pqpqpqpqrrtststs).
Thuật toán
- Duyệt chuỗi mã hóa, tách
temp(chữ cái) vàoccurrence(số). - Ghi
tempvàoencodedđúngoccurrencelần (nếu occurrence=0 thì ghi 1 lần). - Trả về
encoded[k-1].
Ví dụ code
def find_kth_char(s, k):
encoded = ""
occurrence = 0
i = 0
while i < len(s):
temp = ""
occurrence = 0
while i < len(s) and 'a' <= s[i] <= 'z':
temp += s[i]
i += 1
while i < len(s) and '1' <= s[i] <= '9':
occurrence = occurrence * 10 + ord(s[i]) - ord('0')
i += 1
for _ in range(1, occurrence + 1):
encoded += temp
if occurrence == 0:
encoded += temp
return encoded[k - 1]
s = "pq4r2ts3"
k = 11
print(find_kth_char(s, k))
Input
"pq4r2ts3", 11
Output
t