本题的重点在于:如何判断字符串中的字符类型是否包括四种中的三种,以及字符串中是否有长度大于2的重复子串。这里采用暴力解法。对于问题一,可以定义个包含四个元素的数组,遍历字符串,如果找到某个类型的字符,则令相应的数组位置为1。遍历结束后统计数组中1的个数,如果大于或者等于3表示符合要求。对于问题二,可以定义两个指针,第一个指针位于开头,第二个指针从第三个位置开始,圈出三个字符构成子字符串,依次匹配两个字符串是否相等。
#include <iostream>
#include <string>
#include <vector>
#include "string.h"
using namespace std;
// 判断字符串中的字符类型是否符合要求
bool stringType(string s) {
vector<int> s_type(4, 0);
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') { s_type[0] = 1; }
else if (s[i] >= 'a' && s[i] <= 'z') { s_type[1] = 1; }
else if (s[i] >= 'A' && s[i] <= 'Z') { s_type[2] = 1; }
else { s_type[3] = 1; }
}
int num = 0;
for (int i = 0; i < 4; i++) { if (s_type[i] == 1) num++; }
if (num >= 3) return true;
else return false;
}
// 判断字符串是否有长度大于2的重复子串
// 暴力解法
bool stringRepeat(string s) {
int i = 0;
int num = 3;
while (i < s.size() - 2) {
for (int j = num + i; j < s.size() - 2; j++) {
string s1 = s.substr(i, 3);
string s2 = s.substr(j, 3);
const char *s1_c = s1.c_str();
const char *s2_c = s2.c_str();
if (strstr(s1_c, s2_c)) { return false; }
else { continue; }
}
i++;
}
return true;
}
int main() {
string s;
vector<string> res;
while (cin >> s) {
if (s.size() > 8 && stringType(s) && stringRepeat(s)) {
cout << "OK" << endl;
} else {
cout <<"NG"<<endl;
}
}
for (vector<string>::iterator iter = res.begin(); iter != res.end(); iter++) {
cout << *iter << endl;
}
return 0;
}