學習資料:https://programmercarl.com/0344.反轉字串.html#演算法公開課
在python中字串不可變,所以要增加空間 lst=list(str)
344.反轉字串(reverse庫函式的基本程式碼)
點選檢視程式碼
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s)-1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return s
點選檢視程式碼
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def reverse_substring(text):
left, right = 0, len(text)-1
while left < right:
text[left], text[right] = text[right], text[left]
left += 1
right -= 1
return text
# 每2k距離執行一次反轉
ls = list(s)
for i in range(0, len(ls), 2*k):
ls[i:i+k]=reverse_substring(ls[i:i+k])
return ''.join(ls)
卡碼網 54.替換數字
點選檢視程式碼
class Solution:
def change(self, s):
lst = list(s)
for i in range(len(lst)):
if lst[i].isdigit():
lst[i] = "number"
return ''.join(lst)