题解 | #密码验证合格程序#
密码验证合格程序
http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
朴实无华的C语言解法,代码白痴,浅显易懂
#include <stdio.h>
#include <string.h>
int
main(void)
{
char password[102] = {0};
int password_len = 0, idx = 0, idx2 = 0;
int contain_num = 0;
int contain_A_letter = 0;
int contain_a_letter = 0;
int contain_other = 0;
int same_cnt = 0;
while(EOF != scanf("%s",password))
{
/* 判断长度超过8位 */
password_len = strlen(password);
if (password_len <= 8)
{
printf("NG\n");
memset(password, 0, 102);
continue;
}
/* 检查密码包含字母数字其他符号 */
contain_num = 0
contain_A_letter = 0;
contain_a_letter = 0;
contain_other = 0;
for (idx = 0; idx < password_len; idx++)
{
if (password[idx] <= '9' && password[idx] >= '0')
{
contain_num = 1;
}
else if(password[idx] <= 'Z' && password[idx] >= 'A')
{
contain_A_letter = 1;
}
else if(password[idx] <= 'z' && password[idx] >= 'a')
{
contain_a_letter = 1;
}
else
{
contain_other = 1;
}
}
if (contain_num + contain_A_letter + contain_a_letter + contain_other < 3)
{
printf("NG\n");
memset(password, 0, 102);
continue;
}
/* 采用错位比较法
* A b c 4 5 6 4 5 6 主串不动
* | | | | | | | | 每滑动一个字符,比较重叠部分,重叠部分超过3个连续的相同字符则非法
* A b c 4 5 6 4 5 6 >>>>子串向右滑动
*/
same_cnt = 0;
for (idx = 1; idx < password_len - 2 && same_cnt < 3; idx++)
{
for(idx2 = 0; idx2 < password_len - idx && same_cnt < 3; idx2++)
{
if((password[idx2]==password[idx2+idx]))
{
same_cnt++;
}
else
{
same_cnt = 0;
}
}
}
if(same_cnt >= 3)
{
printf("NG\n");
memset(password, 0, 102);
continue;
}
printf("OK\n");
memset(password, 0, 102);
}
}