解题官方分析已经很清楚,接下来对代码进行一定备注与参考:这其中最难得一部分在大与20的密码检测时,所带来的复杂变化,通过不断分析给出的3个连续字符可能出现的各种情况来进行分析,进而将代码写出来!
class Solution(object):
def strongPasswordChecker(self, password):
"""
:type password: str
:rtype: int
"""
length = len(password)
key = 0
sum = 0
replace = 0
cursor = '#'
low_str, upper_str, digital = False,False,False #判断是否有大小写的一种比较性能高
#的方法
for ch in password:
if ch.islower():
low_str = True
if ch.isupper():
upper_str = True
if ch.isdigit():
digital = True
sum = low_str + upper_str + digital
if length < 6:
return max(6-length,3-sum)
elif length <= 20:
for ch in password:
if ch == cursor:
key = key + 1
else:
replace = replace + key // 3
cursor=ch
key = 1
replace = replace + key // 3
return max(3-sum, replace)
else:
rm2 = 0
remove = length - 20
for ch in password:
if ch == cursor:
key = key + 1
else:
if remove > 0 and key >= 3:
if key % 3 == 0:
remove = remove - 1
replace = replace - 1
elif key % 3 == 1:
rm2 += 1
replace += key // 3
key = 1
cursor = ch
if remove > 0 and key >= 3:
if key % 3 == 0:
remove = remove - 1
replace = replace - 1
elif key % 3 == 1:
rm2 += 1
replace = replace + key // 3
key_2 = min(rm2,replace,remove//2) #对于key%3=1,由于每次删2个,才减一次
#replace故第二才考虑
replace -= key_2
remove -= key_2*2
key_3 = min(replace,remove//3) #对于key%3=2,由于没有对replace的减少
#最后考虑
remove -= key_3*3
replace -= key_3
return length - 20 + max(3-sum,replace)