密碼驗證合格程序(C++華爲機試)

解題思路:

(1)判斷字符串的大小是否大於8

(2)使用hash table,存儲四種類型字符出現的次數

(3)依次取前面3個字符,與後面剩下的字符組成的字符串進行模式匹配


#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

bool atleast3(const string &str) {
    int a[4]={0};
    for(auto&& w:str) {
        if(w>='A'&&w<='Z') a[0]=1;
        else if(w>='a'&&w<='z') a[1]=1;
        else if(w>='0'&&w<='9') a[2]=1;
        else a[3]=1;
    }
    int sum = 0;
    for(int i=0;i<4;i++) sum+=a[i];
    if(sum>=3) return true;
    else return false;
}

bool norepeat(const string &str) {
    string txt,pattern;
    for(int i=0;i+5<str.length();i++) {
        pattern = str.substr(i,3);
        txt = str.substr(i+3);
        if(txt.find(pattern)!=string::npos) return false;
    }
    return true;
}


int main() {
    string str;
    while(cin>>str) {
        if(str.length()<=8) cout<<"NG"<<endl;
        else if(!atleast3(str)) cout<<"NG"<<endl;
        else if(!norepeat(str)) cout<<"NG"<<endl;
        else cout<<"OK"<<endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章