344. 反转字符串
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
right = len(s) - 1
for i in range(len(s) // 2):
s[i], s[right] = s[right], s[i]
right -= 1
return s
541. 反转字符串II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def revereSub(s):
right = len(s) - 1
for i in range(len(s) // 2):
s[i], s[right] = s[right], s[i]
right -= 1
return s
s = list(s)
length = len(s)
length_left = length - 2 * k
s[:k] = revereSub(s[:k])
cnt = 1
while length_left >= 2 * k: # 边界判断条件要设置好
s[2 * cnt * k : 2 * cnt * k + k] = revereSub(s[2 * cnt * k : 2 * cnt * k + k])
cnt += 1
length_left -= 2 * k
if 0 < length_left <= k: # 第一次写成<K
s[-length_left:] = revereSub(s[-length_left:])
elif k < length_left < 2 * k:
s[-length_left : - length_left + k] = revereSub(s[-length_left : - length_left + k])
res = ''
for i in s:
res += i
return res
剑指offer05. 替换空格
class Solution:
def replaceSpace(self, s: str) -> str:
st = ''
for c in s:
if c == ' ':
c = '%20'
st += c
return st
不使用额外空间
class Solution:
def replaceSpace(self, s: str) -> str:
s = list(s)
extend = s.count(' ')
s.extend(' ' * 2 * extend) # 往后扩展2*空格数
left = len(s) - extend * 2 - 1 # 左指针指向扩展前最后一位
right = len(s) - 1 # 右指针指向最后一位
while left >= 0: # 边界条件 左指针指向第一位
'''当左指针不指向空格, 赋值给右指针, 左右指针左移一位
当左指针指向空格, 右指针及前三位赋值为 ’%20‘, 左指针左移一位, 右指针左移三位
'''
if s[left] != ' ':
s[right] = s[left]
right -= 1
else:
s[right - 2:right + 1] = '%20'
right -= 3
left -= 1
return ''.join(s)
剑指offer 58. 左旋转字符串
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
s = list(s)
length = len(s)
s.extend(' ' * n)
for i in range(n):
s[length + i] = s[i]
return ''.join(s[n:])
151. 反转字符串中的单词
class Solution:
def reverseWords(self, s: str) -> str:
start = 0
end = 0
l = list()
'''先去除前后空格'''
for i in range(len(s)):
if s[i] != ' ':
start = i
break
for j in range(len(s) - 1, 0, -1):
if s[j] != ' ':
end = j
break
s = s[start : end + 1]
'''反转字符串'''
for i in s:
if i == ' ' and l[-1] == ' ':
continue
else:
l.append(i)
right = len(l) - 1
for left in range(len(l)//2):
l[left], l[right] = l[right], l[left]
right -= 1
fast = 0
slow = 0
a = []
'''反向输出'''
while fast <= len(l) - 1:
while l[fast] != ' ' and fast < len(l) - 1:
fast += 1
if fast == len(l) - 1:
a.extend(reversed(l[slow:fast+1]))
break
a.extend(reversed(l[slow:fast]))
a.extend(l[fast])
fast += 1
slow = fast
return ''.join(a)