classSolution: defreverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left = 0 right = len(s) - 1 while left < right: # s[left], s[right] = s[right], s[left] # Python 的一项语法糖,它可以在不借助临时变量的情况下直接交换两个变量的值 temp = s[left] s[left] = s[right] s[right] = temp left += 1 right -= 1
Leetcode541 反转字符串Ⅱ
每隔2k个字符,反转前k个,后k个不动
当循环结束时,判断剩余字符数量的区间,做不同的反转操作
Python代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defreverseStr(self, s: str, k: int) -> str: length = len(s) i = 0 res = [] while i < length and i+2*k <= length: temp = s[i:i+k][::-1] res.append(temp) res.append(s[i+k:i+2*k]) i = i + 2*k if length - i < k: temp = s[i:][::-1] res.append(temp) if length - i < 2*k and length - i >= k: temp = s[i:i+k][::-1] res.append(temp) res.append(s[i+k:]) return''.join(res)
Leetcode151 翻转字符串里的单词
首先用一个split函数分割字符串
再用双指针,同样的反转字符串的操作
最后用 ' '.join()合并就可以了
Python代码如下:
1 2 3 4 5 6 7 8 9 10
class Solution: def reverseWords(self, s: str) -> str: words = s.split() left = 0 right = len(words) - 1 while left < right: words[left], words[right] = words[right], words[left] left += 1 right -= 1 return ' '.join(words)