①双指针或者range
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
# 该方法已经不需要判断奇偶数,经测试后时间空间复杂度比用 for i in range(len(s)//2)更低
# 因为while每次循环需要进行条件判断,而range函数不需要,直接生成数字,因此时间复杂度更低。推荐使用range
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# 或者
n = len(s)
for i in range(n // 2):
s[i], s[n - i - 1] = s[n - i - 1], s[i]
②切片
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
③栈
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
stack = []
for char in s:
stack.append(char)
for i in range(len(s)):
s[i] = stack.pop()
class Solution:
def reverseWords(self, s: str) -> str:
result_list = []
# 使用滑动窗口
slow, fast = 0, 0
while fast < len(s):
if s[fast] == " ":
if fast -slow >= 1 and s[slow] != " ":
result_list.append(s[slow:fast])
slow = fast
# 向前加1 也很关键!因为当前fast为空,向前一步保证slow的内容不为空
slow += 1
# 特殊情况判断
elif fast == len(s) - 1:
if fast - slow >= 0 and s[slow] != " ":
result_list.append(s[slow:fast+1])
fast += 1
return " ".join(result_list[::-1])
另一种方式:使用split
class Solution:
def reverseWords(self, s: str) -> str:
# 将字符串拆分为单词,即转换成列表类型 split() 不传参 去除了所有空格
words = s.split()
# 反转单词
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
# 将列表转换成字符串
return " ".join(words)
还有一种方法,就是麻烦而已,空间是常数级别的
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# if needle in haystack:
# index1 = haystack.index(needle)
# return index1
# return -1
if len(haystack) == len(needle) and haystack == needle:
return 0
for i in range(len(haystack) - len(needle) + 1):
print(haystack[i:len(needle)])
if haystack[i:i + len(needle)] == needle:
return i
return -1
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
# 有一个隐藏条件是s至少两个字母的 要不然一个字母就是它自己本身了不是子串了
# count = 1
# for i in range(len(s) - 1):
# k = len(s) // count
# if s[0:count] * k == s:
# return True
# count += 1
# return False
return s in (s * 2)[1:-1]