344. Reverse String
to reverse a string in O(n), iterate through the string and swap the head and tail and move toward the center.
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
break the problem into 2 pieces. iterate every 2k and reverse only first k with a reverse function.
class Solution:
def reverseStr(self, s: str, k: int) -> str:
def reverse_sub_str(st):
left = 0
right = len(st) - 1
while left < right:
st[left], st[right] = st[right], st[left]
left += 1
right -= 1
return st
res = list(s)
for i in range(0, len(s), 2*k):
if i+k < len(res) - 1:
res[i:i+k] = reverse_sub_str(res[i:i+k])
else:
res[i:] = reverse_sub_str(res[i:])
return ''.join(res)
剑指Offer 05.替换空格
class Solution:
def replaceSpace(self, s: str) -> str:
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.翻转字符串里的单词
1. reverse the whole list
2. reverse every word
3. remove excess spaces
class Solution:
def reverseWords(self, s: str) -> str:
# method 1 - Rude but work & efficient method.
s_list = [i for i in s.split(" ") if len(i) > 0]
return " ".join(s_list[::-1])
# method 2 - Carlo's idea
def trim_head_tail_space(ss: str):
p = 0
while p < len(ss) and ss[p] == " ":
p += 1
return ss[p:]
# Trim the head and tail space
s = trim_head_tail_space(s)
s = trim_head_tail_space(s[::-1])[::-1]
pf, ps, s = 0, 0, s[::-1] # Reverse the string.
while pf < len(s):
if s[pf] == " ":
# Will not excede. Because we have clean the tail space.
if s[pf] == s[pf + 1]:
s = s[:pf] + s[pf + 1:]
continue
else:
s = s[:ps] + s[ps: pf][::-1] + s[pf:]
ps, pf = pf + 1, pf + 2
else:
pf += 1
return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions,
剑指Offer58-II.左旋转字符串
reverse the first n letters,
reverse the rest of the string
reverse the whole string
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
s = list(s)
s[0:n] = list(reversed(s[0:n]))
s[n:] = list(reversed(s[n:]))
s.reverse()
return "".join(s)
1万+

被折叠的 条评论
为什么被折叠?



