LeetCode 筆記 - 2075. Decode the Slanted Ciphertext

題目在此 2075. Decode the Slanted Ciphertext

給定一個字串,這個字串是由使用傾斜轉置密碼轉換而來,請問原本的字串是什麼?

解題思維

就直接模擬轉換過程就可以了,可以注意的是不要試圖操作字串而是 index,這樣會快很多。image 106

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:

if rows == 1:
return encodedText

str_size = len(encodedText)
column = str_size // rows

result = []
offset = 0
index = 0

while offset < column:
result.append(encodedText[index])
index += (column + 1)

if str_size <= index:
offset += 1
index = offset

return ''.join(result).rstrip()
image 106

相關文章