题解 | #密码验证合格程序#
密码验证合格程序
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; }