题目链接:
1、反转字符串
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i,j = 0,len(s)-1
while i<j:
s[i],s[j] = s[j],s[i]
i+=1
j-=1
2、反转字符串II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
a = list(s)
size = len(a)
for i in range(0,size,2*k):
a[i:i+k] = reversed(a[i:i+k])
return ''.join(a)
3、反转字符串中的单词
class Solution:
def reverseWords(self, s: str) -> str:
if not s:
return ''
s = s.split()
res = ''
for item in s:
res+=item[::-1]+' '
return res.rstrip()
总结:字符串反转多用双指针和reversed等函数。