Leetcode:(Python)(String) Reverse String II

許博淳
數據共筆
Published in
4 min readMar 26, 2023

題目連結:https://leetcode.com/problems/reverse-string-ii/description/

題意說明

  • 題目會給予字串 S,以及長度 k
  • 字串S的 0-k字元要反序,k+1–2k要正序,2k+1–3k要反序 . . .

初始想法

  • 迴圈逐個字元往後走
  • 每 k個輸出一次
  • 要有變數確定要反序還是正序

實作程式碼

class Solution:
def reverseStr(self, s: str, k: int) -> str:
# 正序或反序
is_reverse = True
# 累計多少個字元
counter = 0
output_S = ''
temp_S = ''

for char in s:
# 當累積 k個就要輸出,同時改變順序
if counter == k:
output_S = output_S + temp_S
temp_S = ''
is_reverse = not is_reverse
counter =0
# 反序由前堆疊字串
if is_reverse:
temp_S = char + temp_S
counter = counter+1
# 正序由後堆疊字串
else:
temp_S = temp_S + char
counter = counter+1

output_S = output_S + temp_S

return output_S

結果很不妙阿 XD

反思問題

  • 迴圈其實不用逐個字元,可以一次走 k個字元,這樣甚至不用 counter

實作程式碼

class Solution:
def reverseStr(self, s: str, k: int) -> str:
is_reverse = True
begin = 0
output_s = ''

for end in range(k,len(s),k):
if is_reverse:
output_s = output_s + s[begin:end][::-1]
else:
output_s = output_s + s[begin:end]
is_reverse = not is_reverse
begin = end

if is_reverse:
output_s = output_s + s[begin:][::-1]
else:
output_s = output_s + s[begin:]

return output_s

最差的結果也好過原本的中位數

最佳結果非常好

參考他人解法

解法連結:

不能改變字串內容,但如果轉成 list就可以

解法連結:https://leetcode.com/problems/reverse-string-ii/solutions/343424/python-3-solution-using-recursion-efficient-3-liner-with-explanation/?orderBy=most_votes&languageTags=python3

寫成遞迴也是很酷

class Solution:
def reverseStr(self, s: str, k: int) -> str:
if len(s) < k:
return s[::-1]
elif len(s) < 2*k:
return s[:k][::-1]+s[k:]
else:
return s[:k][::-1]+s[k:2*k]+self.reverseStr(s[2*k:],k)

--

--