当前位置: 首页 > news >正文

Python | Leetcode Python题解之第420题强密码检验器

题目:

题解:

class Solution:def strongPasswordChecker(self, password: str) -> int:n = len(password)has_lower = has_upper = has_digit = Falsefor ch in password:if ch.islower():has_lower = Trueelif ch.isupper():has_upper = Trueelif ch.isdigit():has_digit = Truecategories = has_lower + has_upper + has_digitif n < 6:return max(6 - n, 3 - categories)elif n <= 20:replace = cnt = 0cur = "#"for ch in password:if ch == cur:cnt += 1else:replace += cnt // 3cnt = 1cur = chreplace += cnt // 3return max(replace, 3 - categories)else:# 替换次数和删除次数replace, remove = 0, n - 20# k mod 3 = 1 的组数,即删除 2 个字符可以减少 1 次替换操作rm2 = cnt = 0cur = "#"for ch in password:if ch == cur:cnt += 1else:if remove > 0 and cnt >= 3:if cnt % 3 == 0:# 如果是 k % 3 = 0 的组,那么优先删除 1 个字符,减少 1 次替换操作remove -= 1replace -= 1elif cnt % 3 == 1:# 如果是 k % 3 = 1 的组,那么存下来备用rm2 += 1# k % 3 = 2 的组无需显式考虑replace += cnt // 3cnt = 1cur = chif remove > 0 and cnt >= 3:if cnt % 3 == 0:remove -= 1replace -= 1elif cnt % 3 == 1:rm2 += 1replace += cnt // 3# 使用 k % 3 = 1 的组的数量,由剩余的替换次数、组数和剩余的删除次数共同决定use2 = min(replace, rm2, remove // 2)replace -= use2remove -= use2 * 2# 由于每有一次替换次数就一定有 3 个连续相同的字符(k / 3 决定),因此这里可以直接计算出使用 k % 3 = 2 的组的数量use3 = min(replace, remove // 3)replace -= use3remove -= use3 * 3return (n - 20) + max(replace, 3 - categories)

http://www.mrgr.cn/news/31533.html

相关文章:

  • 煤矿智慧矿井数据集 (1.煤矿采掘工作面智能分析数据集2.煤矿井下钻场智能分析数据集 )
  • zabbix7.0容器化部署测试--(1)准备容器镜像
  • Rust 文件与 IO
  • 【Python】探索 Errbot:多功能聊天机器人框架
  • SOAP 实例
  • C 标准库 - <ctype.h>
  • Python中使用Scikit-learn进行线性回归分析的实用指南
  • 如何在 PHP 中处理 MySQL 的结果集
  • 关于机器学习和深度学习的区别有哪些?
  • 道路坑洞分割数据集/道路裂纹分割数据集
  • golang学习笔记31——golang 怎么实现枚举
  • AI学习指南深度学习篇-Adagrad超参数调优与性能优化
  • Java对象一口气讲完!φ(* ̄0 ̄)
  • 详细分析分布式事务场景、理论基础以及解决方法
  • 松材线虫目标检测数据集,12522张图-纯手工标注
  • python软体使用Matplotlib设计一个数据可视化工具
  • AI学习指南深度学习篇-Adagrad的Python实践
  • WEB 编程:富文本编辑器 Quill 配合 Pico.css 样式被影响的问题
  • C#开源的一个能利用Windows通知栏背单词的软件
  • 3、无线通信系统的组成