代码随想录算法训练营|344.反转字符串;541. 反转字符串II;05.替换空格;151.翻转字符串里的单词;58-II.左旋转字符串
344.反转字符串
题目链接: 344.反转字符串
文档讲解: 代码随想录
题目难度:简单
思路:双指针
时间复杂度:O(n)
下面展示 代码
:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# 双指针
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
541. 反转字符串II
题目链接: 541. 反转字符串II
文档讲解: 代码随想录
题目难度:简单
思路:利用for循环找到2k的位置,再搭配反转字符串I即可
代码
如下:
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def reverseString(s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# 双指针
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return s
# 利用for循环找到2k的位置
res = list(s)
for i in range(0, len(s), 2*k):
# 字符串末尾如果超过最大长度,则会返回至字符串最后一个值,这个特性可以避免一些边界条件的处理
res[i:i+k] = reverseString(res[i:i+k])
return ''.join(res)
05.替换空格
题目链接: 05.替换空格
文档讲解: 代码随想录
题目难度:简单
思路:1、双指针均从后往前遍历;2、需要使用额外的 2*空格 个空间来存放%20(原始的空格已经占了1格)。
注:python中,字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能为O(1)
时间复杂度:O(n)
代码
如下:
class Solution:
def replaceSpace(self, s: str) -> str:
# python中,字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能为O(1)
# res = []
# for i in range(len(s)):
# if s[i] == ' ':
# res.append('%20')
# else:
# res.append(s[i])
# return ''.join(res)
# 双指针从后往前遍历,时间复杂度为o(n)
# 需要使用额外的 2*空格 个空间来存放%20(原始的空格已经占了1格)
counter = s.count(' ')
res = list(s)
res.extend([' '] * counter* 2)
left, right = len(s) -1 , len(res) -1
while left >= 0:
if s[left] != ' ':
res[right] = s[left]
right -= 1
else:
res[right-2:right+1] = '%20'
right -= 3
left -= 1
return ''.join(res)
151.翻转字符串里的单词
题目链接: 151.翻转字符串里的单词
文档讲解: 代码随想录
题目难度:简单
思路:split+双指针
时间复杂度:O(n)
代码
如下
class Solution:
def reverseWords(self, s: str) -> str:
# 非O(1)版本
#1、去掉多余空格;2、字符串全翻转;3、单词全翻转
# s = s.strip()
# s = s[::-1]
# s = ' '.join(word[::-1] for word in s.split())
# return s
# O(1)版本:双指针法
words = s.split()
# s = "the sky is blue"; words = ["the","sky","is","blue"]
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
return ' '.join(words)
58-II.左旋转字符串
题目链接: 58-II.左旋转字符串
文档讲解: 代码随想录
题目难度:简单
思路:切片
时间复杂度:O(n)
代码
如下
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
#切片
return s[n:] + s[0:n]