这个题解的思路是分别检查密码是否满足三条规则:
1. 检查密码长度是否在6到20之间,计算需要插入或删除的字符数。
2. 检查密码是否包含小写字母、大写字母和数字,计算需要替换的字符数。
3. 将密码转换为连续字符的分组列表,迭代地应用删除操作,使得尽可能消除连续三个相同字符的情况。最后计算需要替换的分组数。
最终返回所需的最少修改步数,即删除操作数 + max(需要的类型替换数, 需要的分组替换数, 需要的插入数)。
时间复杂度: O(n * num_required_deletes)
空间复杂度: O(n)
```python
import itertools
class Solution:
lowercase = set('abcdefghijklmnopqrstuvwxyz')
uppercase = set('ABCDEFGHIJKLMNOPQRSTUFVWXYZ')
digit = set('0123456789')
def strongPasswordChecker(self, s: str) -> int:
characters = set(s)
# 检查规则(2),计算需要的类型替换数
needs_lowercase = not (characters & self.lowercase)
needs_uppercase = not (characters & self.uppercase)
needs_digit = not (characters & self.digit)
num_required_type_replaces = int(needs_lowercase + needs_uppercase + needs_digit)
# 检查规则(1),计算需要的插入数和删除数
num_required_inserts = max(0, 6 - len(s))
num_required_deletes = max(0, len(s) - 20)
# 检查规则(3)
# 将密码转换为连续字符的分组列表
groups = [len(list(grp)) for _, grp in itertools.groupby(s)]
# 迭代地应用最佳的删除操作
def apply_best_delete():
argmin, _ = min(
enumerate(groups),
# 忽略长度小于3的分组,除非没有其他选择
key=lambda it: it[1] % 3 if it[1] >= 3 else 10 - it[1],
)
groups[argmin] -= 1
for _ in range(num_required_deletes):
apply_best_delete()
# 计算需要的分组替换数
num_required_group_replaces = sum(
group // 3
for group in groups
)
return (
# 删除操作数
num_required_deletes
# 类型替换数可以被插入数或分组替换数替代
+ max(
num_required_type_replaces,
num_required_group_replaces,
num_required_inserts,
)
)
```