mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
678 字
3 分钟
python算法学习之大O表示法与变位词
2026-01-17

大O表示法#

大O表示法(Big O Notation)是用于描述算法时间复杂度的数学符号,表示算法的运行时间或空间需求随输入规模增长的变化趋势。 例如:实际运行时间:T(n) = 3n² + 2n + 100 大O表示:O(n²) ← 只保留最高阶项,忽略系数 当n很大时:n=1000: 3*(1000²)=3,000,000 vs 2*1000=2000 vs 100 低阶项和常数可以忽略不计!

一、什么是变位词?#

变位词(Anagram) 是指由相同字母重新排列形成的单词或短语。 核心特征

字母相同:包含完全相同的字母集合
顺序不同:字母的排列顺序不同
长度相同:单词长度必须相等
大小写无关:通常忽略大小写差异

变位词示例#

```python
anagram_pairs = [
("listen", "silent"), # 经典例子
("earth", "heart"), # 字母重组
("evil", "vile"), # 短词变位
("debit card", "bad credit"), # 短语变位
("Eleven plus two", "Twelve plus one"), # 有趣的长短语
]
```

非变位词示例#

```python
not_anagrams = [
("hello", "hell"), # 长度不同
("test", "best"), # 字母不同
("apple", "apples"), # 字母数量不同
]
```

二、判断变位词的多种方法#

1:排序比较法#

```python
def is_anagram_sort(s1: str, s2: str) -> bool:
"""方法1:排序比较 - O(n log n)时间,O(n)空间"""
# 清理字符串:去空格、转小写
s1_clean = ''.join(s1.lower().split())
s2_clean = ''.join(s2.lower().split())
# 长度不同直接返回False
if len(s1_clean) != len(s2_clean):
return False
# 排序后比较
return sorted(s1_clean) == sorted(s2_clean)
```

方法2:字符计数法#

```python
def is_anagram_counter(s1: str, s2: str) -> bool:
"""方法2:字符计数 - O(n)时间,O(1)空间(固定大小数组)"""
# 清理字符串
s1_clean = ''.join(s1.lower().split())
s2_clean = ''.join(s2.lower().split())
if len(s1_clean) != len(s2_clean):
return False
# 假设只包含小写英文字母(26个)
counter = [0] * 26
# 统计第一个字符串的字符频率
for ch in s1_clean:
if 'a' <= ch <= 'z':
counter[ord(ch) - ord('a')] += 1
# 减去第二个字符串的字符频率
for ch in s2_clean:
if 'a' <= ch <= 'z':
index = ord(ch) - ord('a')
counter[index] -= 1
if counter[index] < 0: # 提前结束
return False
# 检查是否所有计数都为0
return all(count == 0 for count in counter)
```

方法3:质数乘积法(巧妙但有限制)#

```python
def is_anagram_prime(s1: str, s2: str) -> bool:
"""方法3:质数乘积法 - O(n)时间,O(1)空间"""
# 给每个字母分配一个唯一的质数
primes = {
'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11,
'f': 13, 'g': 17, 'h': 19, 'i': 23, 'j': 29,
'k': 31, 'l': 37, 'm': 41, 'n': 43, 'o': 47,
'p': 53, 'q': 59, 'r': 61, 's': 67, 't': 71,
'u': 73, 'v': 79, 'w': 83, 'x': 89, 'y': 97, 'z': 101
}
s1_clean = ''.join(s1.lower().split())
s2_clean = ''.join(s2.lower().split())
if len(s1_clean) != len(s2_clean):
return False
def calculate_product(s):
product = 1
for ch in s:
if 'a' <= ch <= 'z':
product *= primes[ch]
return product
return calculate_product(s1_clean) == calculate_product(s2_clean)
```
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

python算法学习之大O表示法与变位词
https://tclothes.online/posts/算法1/sf1/
作者
衣服修改
发布于
2026-01-17
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时