前言

使用语言 Python, 只针对 LC Medium 和 Hard 题, 面向面试刷题
Note: 除非你面前端 (加上 JS) , 否则统一使用 Python 进行刷题


基本操作

s = "hello"

# 取字符
s[0] # "h"
s[-1] # "o" (最后一个)

# 长度
len(s)

# string 是 immutable,不能直接改
s[0] = "H" # ❌ 报错
# 拼接
s1 + s2 # "hello" + "world" = "helloworld"
char * 3 # "a" * 3 = "aaa"

# list 转 string
"".join(["a", "b", "c"]) # "abc"
"-".join(["a", "b", "c"]) # "a-b-c"

# string 转 list
list("abc") # ["a", "b", "c"]

# 切片
s[1:3] # "el" (index 1 到 2)
s[:3] # "hel" (前 3 个)
s[2:] # "llo" (从 index 2 到最后)
s[::-1] # "olleh" (反转)

查找

s.find("ll")               # 2 (返回 index,找不到返回 -1)
s.index("ll") # 2 (找不到会报错)
"ll" in s # True
s.count("l") # 2 (出现次数)

判断

s.isalpha()                # 是否全是字母
s.isdigit() # 是否全是数字
s.isalnum() # 是否全是字母或数字
s.startswith("he") # True
s.endswith("lo") # True

转换

s.lower()                  # "hello"
s.upper() # "HELLO"
s.strip() # 去掉首尾空格
s.replace("l", "x") # "hexxo"
s.split(" ") # "a b c" → ["a", "b", "c"]

# 排序字符串(返回字符列表)
s = "eat"
sorted(s) # ['a', 'e', 't']

构建字符串

# 方法 1:用 list 拼接再 join(推荐)
result = []
for char in s:
result.append(char)
return "".join(result)

# 方法 2:直接拼接(小规模可以)
result = ""
result += "a"

回文判断

# 整个字符串是不是回文
s == s[::-1]

# 双指针判断(更省空间)
def isPalindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True

字符比较

# ASCII 比较
'a' < 'b' # True
ord('a') # 97
chr(97) # 'a'

# 大小写敏感
'A' < 'a' # True (65 < 97)

题目

LC 3

实际上是 set 加上 two pointer

LC 5

需要一个方法 expand(left, right), s[left] == s[right] 的情况下 left -= 1, right += 1

LC 68

不算特别复杂,但是要考虑不同的情况

LC 165

split('.') 把 version 中的数字分开

LC 151

如果在不用 split() 的情况下, 用 i 去跳过空格, 用 j 去找单词, 然后添加 s[i:j]