主要思路
关键是对第三个密码要求的处理。
主要用到两个string字符串函数,substr和find。
循环遍历每一个字符,取出当前字符及之后长度为3的子串(因为题目要求不允许长度大于2的子串重复,我们取长度为3尝试即可),然后从后面的序列中查找该子串,如果找到了说明有重复,反之,合法。
附:substr,find函数原型
string substr (size_t pos = 0, size_t len = npos) const;作用就是截取主串的一个子串,第一个参数是主串的位置,即想从主串哪里开始截取,第二个参数是希望该子串的长度。
size_t find (const string& str, size_t pos = 0) const noexcept;从主串中找子串,第二个参数的意思是从主串的哪里开始查起。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string str;
while(cin>>str) {
int len = str.size();
//1.长度超过8位
if(len<=8) {
cout<<"NG"<<endl;
continue;
}
//2.包括大小写字母.数字.其它符号,以上四种至少三种
int arr[4] = {0};
for(int i = 0;i<len;++i) {
if(str[i]>='0'&&str[i]<='9'){
arr[0] = 1;
}
else if(str[i]>='A'&&str[i]<='Z') {
arr[1] = 1;
}
else if(str[i]>='a'&&str[i]<='z') {
arr[2] = 1;
}
else {
arr[3] = 1;
}
}
int cnt = 0;
for(int i = 0;i<4;i++) {
cnt+=arr[i];
}
if(cnt<3){
cout<<"NG"<<endl;
continue;
}
//3.不能有长度大于2的不含公共元素的子串重复
//(注:其他符号不含空格或换行)
bool flag = true;
for(int i = 0;i<len-3;++i) {
//substr是从i截取子串,长度为n
//第一个参数是位置,第二个是长度
//string substr (size_t pos = 0, size_t len = npos) const;
string sub_str = str.substr(i,3);
//size_t find (const string& str, size_t pos = 0) const noexcept;
size_t found = str.find(sub_str,i+3);//从当前子串之后查找
if(found!=string::npos) {//说明有重复
cout<<"NG"<<endl;
flag = false;
break;
}
}
if(flag)cout<<"OK"<<endl;
}
return 0;
}