题解 | #密码验证合格程序#
密码验证合格程序
http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
HJ20 密码验证合格程序
1.1 解题思路
- 长度超过8位:比较字符串长度
- 包括大小写字母.数字.其它符号,以上四种至少三种:定义一个长度为 4 的数组,上述有一种存在的时候就将对应的数组小标对应的值设置为 1
- 不能有长度大于2的包含公共元素的子串重复:使用长度为 3 的隔窗进行判断,每次移动一位,移出的部分就是已经判断过的
1.2 实例代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
System.out.println(passwordOk(sc.nextLine()) ? "OK" : "NG");
}
}
public static boolean passwordOk(String str) {
// 1. 长度限制
if(str.length() <= 8) {
return false;
}
// 2. 符号限制(只能赋初值1,不嫩累加,因为需要的是种类)
int[] count = new int[4];
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= 'a' && c <= 'z') {
count[0] = 1;
} else if(c >= 'A' && c <= 'Z') {
count[1] = 1;
} else if (c >= '0' && c <= '9') {
count[2] = 1;
} else {
count[3] = 1;
}
}
if(count[0] + count[1] + count[2] + count[3] < 3) {
return false;
}
// 2. 公共字串(隔窗法,窗体大小3)
for(int i = 0; i < str.length() - 3; i++) {
if (str.substring(i + 3).contains(str.substring(i, i + 3))) {
return false;
}
}
return true;
}
}