总结双指针:
- 27 移除元素
- 15 三数之和
- 18 四数之和
- 206 翻转链表
- 142 环形链表2
- 344 反转字符串
344. Reverse String
双指针反转两头,逐一往中间靠,继续反转
541. Reverse String II
要写简洁代码不容易,参考了一下代码
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def reverse_substring(text):
left = 0
right = len(text)-1
while(left<right):
text[left], text[right] = text[right], text[left] #不用temp的写法
left+=1
right-=1
return text
res = list(s)#create a mutable list res with the same characters as s
for cur in range(0,len(s),2*k):
res[cur:cur+k]=reverse_substring(res[cur:cur+k])
return ''.join(res)
1. 使用range(start, end, step)来确定需要调换的初始位置
2. 对于字符串s = 'abc',如果使用s[0:999] ===> 'abc'。字符串末尾如果超过最大长度,则会返回至字符串最后一个值,这个特性可以避免一些边界条件的处理。
3. 用切片整体替换,而不是一个个替换.
注意交换值的简洁写法
定义一个function来简化操作
因为string immutable,所以复制到一个list来操作
这种做法可以处理边界值,当要reverse的string长度小于k时也能操作
kama54代码随想录
【从后向前替换数字字符,也就是双指针法,过程如下:i指向新长度的末尾,j指向旧长度的末尾
其实很多数组填充类的问题,其做法都是先预先给数组扩容带填充后的大小,然后在从后向前进行操作。
这么做有两个好处:
- 不用申请新数组。
- 从后向前填充元素,避免了从前向后填充元素时,每次添加元素都要将添加元素之后的所有元素向后移动的问题。】
这种方法空间复杂度低
但python无法改string
151. Reverse Words in a String
其他语言的话最好用快慢指针,为了空间复杂度为O(1),想不用split(但python不能修改string)
类似27移除元素
有点像bnp那道polynomial的oa
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s.strip()
s = s[::-1]
s = ' '.join(word[::-1] for word in s.split())
#反转两次,一次整个反转,一次只反转每个单词
return s