344.反转字符串
- 使用双指针一个指针指向数组开始的位置,一个指针指向数组结束的位置
- 通过循环让两个指针元素相互交换知道两个指针碰到一起
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
# use two pointer
left = 0
right = len(s) - 1
temp = 0
# iterate the list
while right >= left:
# swap the element
temp = s[right]
s[right] = s[left]
s[left] = temp
right -= 1
left += 1
# return original array
return s
541.反转字符串II
-
判断 i+k <= s.size 才进行反转,保证i+k要在数组范围内
-
反转跟344题逻辑一样写一个函数调用即可
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def subString(text):
# reverse the letter
left = 0
right = len(text)-1
while right >= left:
# sawp
text[left],text[right] = text[right],text[left]
right -= 1
left += 1
return text
# convert the string to list,easy to operate
result = list(s)
for cur in range(0,len(s),2*k):
result[cur:cur+k] = subString(result[cur:cur+k])
return "".join(result)
标签:right,return,cur,反转,II,result,text,字符串,left
From: https://blog.csdn.net/NeighborKing/article/details/141386864