题解 | #密码验证合格程序#
密码验证合格程序
http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
模拟
思路
- 长度小于8,则 NG
- 使用
set
判断密码中字符类型是否超过三种- 代表“数字”、 代表“大写字母”、 代表“小写字母”、 代表“其他字符”
- 若最终输入串
line
对应的set
长度小于 3,则说明密码中字符类型没有超过三种,即 NG
- 重复子串判断 :star::即,判断当前密码串中 “是否存在长度 的重复子串”
- 做法:逆序 遍历
line
,从后向前截取长度为 的子串 ,若当前串中存在和 相同的子串,则indexOf(s3) + 2 < i
,即 NG;否则,则重复上述做法,继续逆序遍历line
- 做法:逆序 遍历
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
outter:
while (in.hasNextLine()) {
String line = in.nextLine();
// 1、长度小于8
if (line.length() <= 8) {
System.out.println("NG");
continue;
}
Set<Integer> set = new HashSet<>();
for (int i = line.length() - 1; i >= 0; i--) {
char c = line.charAt(i);
if (Character.isDigit(c)) {
set.add(0);
} else if (Character.isUpperCase(c)) {
set.add(1);
} else if (Character.isLowerCase(c)) {
set.add(2);
} else { // 特殊字符
set.add(3);
}
// 3、重复子串判断
if (i < line.length() - 2) {
// 截取长度为3的子串
String s3 = line.substring(i, i + 3);
if (line.indexOf(s3) + 2 < i) {
System.out.println("NG");
continue outter;
}
}
}
// 2、字符种类少于三种
if (set.size() < 3) {
System.out.println("NG");
continue;
}
System.out.println("OK");
}
in.close();
}
}