[leetcode]Strong Password Checker

Description

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

It has at least 6 characters and at most 20 characters.
It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
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.

Solution

一道简单的模拟题。只要注意好三中操作的顺序即可。
除了字符串长度<6和>20的情况,其他情况尽量用替换操作。譬如“aaaaa”用删除操作需要三次,而用替换操作只要一次,如”aa1aa”.

附代码:

class Solution {
public:
   int strongPasswordChecker(string s) {
    int n = (int)s.length();
    vector<int> c;
    bool lowercase = false,uppercase = false, digit = false;
    for (int i = 0; i < n; ++i) {
        if ('0' <= s[i] && s[i] <= '9') digit = true;
        if ('a' <= s[i] && s[i] <= 'z') lowercase = true;
        if ('A' <= s[i] && s[i] <= 'Z') uppercase = true;
        int j = i;
        while  (i < n && s[j] == s[i+1]) ++i;
        c.push_back(i - j + 1);
    }
    int add = (digit ? 0 : 1) + (lowercase ? 0 : 1) + (uppercase ? 0 : 1);
    int ans = 0;
    if (n < 6) {
        ans = (6-n);
        if (add > ans) ans += add - ans;
    } else {
        int haveto_delete = (n > 20 ? n-20 : 0);
        ans += haveto_delete;
        int m =(int) c.size();

        for (int i = 0; i < m; ++i) {
            if (c[i] >= 3 ) {
                if (c[i] % 3 == 0 && haveto_delete > 0) {
                    haveto_delete -= 1;
                    c[i] -= 1;
                } else
                    if (c[i] % 3 == 1 && haveto_delete > 1) {
                        haveto_delete -= 2;
                        c[i] -= 2;
                    }
            }
        }
        int change_cnt = 0;
        for (int i = 0; i < m; ++i){
            if (c[i] >= 3 && haveto_delete > 0) {
                int needto_delete = c[i] - 2;
                if (needto_delete <= haveto_delete) {
                    haveto_delete -= needto_delete;
                    c[i] = 2;
                } else {
                    c[i] -= haveto_delete;
                    haveto_delete = 0;
                }
            }
            change_cnt += c[i]/3;
        }
        ans += max(change_cnt, add);
    }
    return ans;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值