344. Reverse String
class Solution(object):
def reverseString(self, s):
s[:] = s[::-1]
class Solution(object):
def reverseString(self, s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
541. Reverse String II
# 双指针p和p2,p表示子串起始位置,p2表示子串第k个位置
class Solution:
def reverseStr(self, s, k):
p = 0
while p < len(s): # 从0开始,以2k长度向后迭代
p2 = p + k # 需要保持不变的子串
s = s[:p] + s[p:p2][::-1] + s[p2:]
p = p + 2 * k
return s
class Solution:
def reverseStr(self, s, k):
def reverse_substring(text):
left, right = 0, len(text) - 1
while left < right:
text[left], text[right] = text[right], text[left]
left += 1
right -= 1
return text
res = list(s)
for cur in range(0, len(s), 2 * k):
res[cur: cur + k] = reverse_substring(res[cur: cur + k])
return ''.join(res)
剑指 Offer 05. 替换空格
class Solution(object):
def replaceSpace(self, s):
res = s.split(" ")
return "%20".join(res)
class Solution:
def replaceSpace(self, s):
n = len(s)
for e, i in enumerate(s[::-1]):
print(i, e)
if i == " ":
s = s[: n - (e + 1)] + "%20" + s[n - e:]
return s
class Solution:
def replaceSpace(self, s):
counter = s.count(' ')
res = list(s)
# 每碰到一个空格就多拓展两个格子,1 + 2 = 3个位置存’%20‘
res.extend([' '] * counter * 2)
# 原始字符串的末尾,拓展后的末尾
left, right = len(s) - 1, len(res) - 1
while left >= 0:
if res[left] != ' ':
res[right] = res[left]
right -= 1
else:
# [right - 2, right), 左闭右开
res[right - 2: right + 1] = '%20'
right -= 3
left -= 1
return ''.join(res)
151. Reverse Words in a String
class Solution:
#1.去除多余的空格
def trim_spaces(self,s):
n = len(s)
left = 0
right = n - 1
while left <= right and s[left] == ' ':
left += 1
while left <= right and s[right] == ' ':
right = right - 1
tmp=[]
while left <= right:
if s[left] != ' ':
tmp.append(s[left])
elif s[left] == ' ' and tmp[-1] != ' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的
tmp.append(s[left])
left += 1
return tmp
#2.翻转字符数组
def reverse_string(self,nums,left,right):
while left
剑指 Offer 58 - II. 左旋转字符串
# 方法一:可以使用切片方法
class Solution:
def reverseLeftWords(self, s, n):
return s[n:] + s[0:n]
# 方法二:也可以使用上文描述的方法,有些面试中不允许使用切片,那就使用上文作者提到的方法
class Solution:
def reverseLeftWords(self, s, n):
s = list(s)
s[0:n] = list(reversed(s[0:n]))
s[n:] = list(reversed(s[n:]))
s.reverse()
return "".join(s)
# 方法三:如果连reversed也不让使用,那么自己手写一个
class Solution:
def reverseLeftWords(self, s, n):
def reverse_sub(lst, left, right):
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
res = list(s)
end = len(res) - 1
reverse_sub(res, 0, n - 1)
reverse_sub(res, n, end)
reverse_sub(res, 0, end)
return ''.join(res)
# 同方法二
# 时间复杂度:O(n)
# 空间复杂度:O(n),python的string为不可变,需要开辟同样大小的list空间来修改
#方法四:考虑不能用切片的情况下,利用模+下标实现
class Solution:
def reverseLeftWords(self, s, n):
new_s = ''
for i in range(len(s)):
j = (i+n)%len(s)
new_s = new_s + s[j]
return new_s