● 344.反转字符串
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left=0
right=len(s)-1
while left<right:
temp=s[left]
s[left]=s[right]
s[right]=temp
left+=1
right-=1
return s
● 541. 反转字符串II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def reverseString(s):
left=0
right=len(s)-1
while left<right:
temp=s[left]
s[left]=s[right]
s[right]=temp
left+=1
right-=1
return s
res=list(s)
for i in range(0,len(res),2*k):
res[i:i+k]=reverseString(res[i:i+k])
return ''.join(res)
● 剑指Offer 05.替换空格
class Solution:
def replaceSpace(self, s: str) -> str:
res=list(s)
for i in range(len(res)):
if res[i]==' ':
res[i]='%20'
return ''.join(res)
● 151.翻转字符串里的单词
class Solution:
def reverseWords(self, s: str) -> str:
s=s.split()
print(s)
left=0
right=len(s)-1
while left<right:
temp=s[left]
s[left]=s[right]
s[right]=temp
left+=1
right-=1
return ' '.join(s)
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(list)
● 剑指Offer58-II.左旋转字符串
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
m=len(s)
temp=n%m
return s[temp:]+s[:temp]