Python 中解密字串的第 k 個字元 - 集 - 2
假設我們有一個編碼字串,其中子字串的重複用子字串後跟子字串的計數來表示。例如,如果字串是“pq2rs2”且 k=5,則輸出將是'r',這是因為解密後的字串是“pqpqrsrs”,第 5 個字元是'r'。我們必須記住,加密子字串的頻率可以超過一位數字。
因此,如果輸入類似於字串 =“pq4r2ts3”且 k = 11,則輸出將是 i,因為字串是 pqpqpqpqrrtststs
為了解決這個問題,我們將遵循以下步驟:
encoded := 空字串
occurrence := 0, i := 0
當 i < str 的大小 時,執行
temp := 空字串
occurrence := 0
當 i < str 的大小 且 str[i] 是字母時,執行
temp := temp + str[i]
i := i + 1
當 i < str 的大小 且 str[i] 是數字時,執行
occurrence := occurrence * 10 + str[i] 的 ASCII 碼 - '0' 的 ASCII 碼
i := i + 1
對於 j 從 1 到 occurrence + 1,遞增 1,執行
encoded := encoded + temp
如果 occurrence 等於 0,則
encoded := encoded + temp
返回 encoded[k - 1]
示例
讓我們看看下面的實現以獲得更好的理解:
def find_kth_char(str, k):
encoded = ""
occurrence = 0
i = 0
while i < len(str):
temp = ""
occurrence = 0
while (i < len(str) and ord(str[i]) >= ord('a') and ord(str[i]) <= ord('z')):
temp += str[i]
i += 1
while (i < len(str) and ord(str[i]) >= ord('1') and ord(str[i]) <= ord('9')):
occurrence = occurrence * 10 + ord(str[i]) - ord('0')
i += 1
for j in range(1, occurrence + 1, 1):
encoded += temp
if occurrence == 0:
encoded += temp
return encoded[k - 1]
str = "pq4r2ts3"
k = 11
print(find_kth_char(str, k))輸入
"pq4r2ts3", 11
輸出
t
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP