学习资料: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)