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=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));
        }
       
    }
}


你可能感兴趣的:(leetcode)