420. Strong Password Checker

A password is considered strong if below conditions are all met:

  1. It has at least 6 characters and at most 20 characters.
  2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
  3. It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).

Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.

Insertion, deletion or replace of any one character are all considered as one change.

思路: 若连续次数超过3,则将其替换字母,使得其连续字母个数不超过3的操作数为

count/3
若总的个数超过20个,则需要删除数字,是3的被数的删除1个,余数为1的需要删除2个,余数为2的需要删除3个。


public class Solution {
    public int strongPasswordChecker(String s) {
        int ans=0;
        boolean hasLower=false,hasUpper=false,hasDigit=false;
        
        int n=s.length();
        if(n<2)
            return 6-n;
        char ch;
        char pre=' ';
     
        int count=1;
        int[] nums=new int[3];
        for(int i=0;i<n;i++){
            ch=s.charAt(i);
            if(ch==pre) count++;
            else{
                if(count>=3){
                    nums[count%3]++;
                    ans+=count/3;
                }
                count=1;
                pre=ch;
                if(ch>='a'&&ch<='z') hasLower=true;
                else if(ch>='A'&&ch<='Z') hasUpper=true;
                else if(ch>='0'&&ch<='9') hasDigit=true;
            }
           
        }
         if(count>=3){
               nums[count%3]++;
               ans+=count/3;
         }
        

        
        int lose=(hasLower?0:1)+(hasUpper?0:1)+(hasDigit?0:1);

        
        if(n>20){
            int remain=n-20;
            if(remain<=nums[0]){
                ans-=remain;
            }
            else if((remain-nums[0])<=2*nums[1])
                ans-=nums[0]+(remain-nums[0])/2;
            else
                ans-=nums[0]+nums[1]+(remain-nums[0]-nums[1]*2)/3;
                
            return remain+Math.max(ans,lose);
            
        }
        else{
            return Math.max(Math.max(ans,lose),(6-n));
        }
       
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值