题解 | #密码验证合格程序#

密码验证合格程序

https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841?tpId=37&tqId=21243&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=3&judgeStatus=undefined&tags=&title=

#include <iostream>
#include <regex>
using namespace std;

int main() {
    string s;
    while (cin >> s) {
        int len = s.length();
        if (len <= 8) {
            cout << "NG"  << endl;
            continue;
        }
        int a = 0, b = 0, c = 0, d = 0;
        //改进:不用计算个数,看它是否出现过即可
        for (int i = 0; i < len; i++) {
            if (s[i] >= 'A' && s[i] <= 'Z') {
                a = 1;
            } else if (s[i] >= 'a' && s[i] <= 'z') {
                b = 1;
            } else if (s[i] >= '0' && s[i] <= '9') {
                c = 1;
            } else {
                d = 1;
            }
        }
        if(a+b+c+d<3){
            cout << "NG"  << endl;
            continue;
        }
        bool flag = false;
        //字串匹配:看能否分割出两个长为3的相同字串即可
        if (len / 2 >= 3) {
            for (int i = 0; i < len - 3; i++) {
                string subs = s.substr(i, 3);
                string sstr = s.substr(3 + i, len - 3 - i);
                string escaped_subs = escapeRegex(subs);//转义特殊字符
                regex pattern(escaped_subs);
                smatch matches;
                if (regex_search(sstr, matches, pattern)) {
                    cout << "NG" << endl;
                    flag = true;
                    break;
                }
            }
        }
        if (!flag) {
            cout << "OK" << endl;
        }
    }
    return 0;
}
// 函数用于转义正则表达式特殊字符,如()分组,$行结束
string escapeRegex(const string& str) {
    string escaped;
    for (char c : str) {
        switch (c) {
            case '.':
            case '^':
            case '$':
            case '*':
            case '+':
            case '?':
            case '|':
            case '(':
            case ')':
            case '[':
            case ']':
            case '{':
            case '}':
                escaped += '\\'; 
            default:
                escaped += c;
        }
    }
    return escaped;
}

全部评论

相关推荐

孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务