[leetcode]Strong Password Checker

来源:互联网 发布:ac100网络隔离 编辑:程序博客网 时间:2024/06/18 08:03

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