HJ20 密码验证合格程序 C/C++

题目链接

主要思路

关键是对第三个密码要求的处理。
主要用到两个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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值