华为机试题HJ20题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
#include <cctype>
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <unordered_map>
using namespace std;
// 获取某个字符串所有长度大于2的子串
bool IsSubStrsDuplicate(const std::string &s)
{
// 暴力枚举出所有s的长度大于2的子串
vector<string> subStrVec;
string sTemp = "";
for (int i = 0; i < s.size() - 1; i ++) {
for (int j = i + 1; j < s.size(); j++) {
sTemp = s.substr(i, j - i + 1);
if (sTemp.size() > 2) {
subStrVec.push_back(sTemp);
}
}
}
// 遍历所有子串,看是否有有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
unordered_map<string,int> wordMap;
for (auto item : subStrVec) {
wordMap[item]++;
}
for (auto item2 : wordMap) {
if (item2.second >= 2) {
return false;
}
}
return true;
}
// 判断某个字符串是否是合格的密码
// 密码要求:
// 1.长度超过8位
// 2.包括大小写字母.数字.其它符号,以上四种至少三种
// 3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
bool isValidPassword(const string &s)
{
// 条件1:长度超过8位
if (s.size() <= 8) {
return false;
}
// 条件2:包括大小写字母.数字.其它符号,以上四种至少三种
// 依次统计大写字母、小写字母、数字、其他符号的总个数
int numCnt = 0, upperCnt = 0, lowerCnt = 0, otherCnt = 0;
for (auto ch : s) {
if (ch >= 'A' && ch <= 'Z') {
upperCnt++;
} else if (ch >= 'a' && ch <= 'z') {
lowerCnt++;
} else if (ch >= '0' && ch <= '9') {
numCnt++;
} else {
otherCnt++;
}
}
int totalCnt = 0;
if (numCnt > 0) {
totalCnt++;
}
if (upperCnt > 0) {
totalCnt++;
}
if (lowerCnt > 0) {
totalCnt++;
}
if (otherCnt > 0) {
totalCnt++;
}
if (totalCnt < 3) {
return false;
}
// 条件3:不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
return IsSubStrsDuplicate(s);
}
int main() {
string s;
while (cin >> s) { // 注意 while 处理多个 case
if (isValidPassword(s)) {
cout << "OK" << endl;
} else {
cout <<"NG" << endl;
}
}
}
// 64 位输出请用 printf("%lld")
查看15道真题和解析