1、完整题目
描述
密码要求:
1.长度超过8位
2.包括大小写字母.数字.其它符号,以上四种至少三种
3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
数据范围:输入的字符串长度满足 1≤n≤100
输入描述:
一组字符串。
输出描述:
如果符合要求输出:OK,否则输出NG
示例1
输入:
021Abc9000 021Abc9Abc1 021ABC9000 021$bc9000
输出:
OK NG NG OK
2、Java代码(提交版)
- str.chars() 获取字符流,通过流的 filter() 方法可以简单地过滤出符合要求的字符,后接 count() 方法计算过滤后的元素个数。
- ".*(.{3,}).*\\1.*" 表示匹配长度 >=3 的不包含公共元素的重复子字符串。这里的 .* 表示任意长度(>=0)的字符串,中间夹杂了 "(.{3,})" 和 "\\1",(.{3,})表示匹配任意长度>=3的字符串,\\1 表示匹配与前面(.{3,})一样的字符串,所以 ".*(.{3,}).*\\1.*" 表示匹配长度 >=3 的不包含公共元素的重复子字符串。具体的Java正则表达式的快速复习可以看博文:Java正则表达式(全面回忆)-CSDN博客
import java.util.Scanner;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.next();
if(!validataLength(str)){
System.out.println("NG");
}else if(!validataChar(str)){
System.out.println("NG");
}else if(Pattern.compile(".*(.{3,}).*\\1.*").matcher(str).find()){
System.out.println("NG");
}else System.out.println("OK");
}
}
public static Boolean validataLength(String str) {
return str.length() > 8;
}
public static Boolean validataChar(String str) {
int count = 0;
if (str.chars().filter(c -> 'A' <= c && c <= 'Z').count() > 0) count++;
if (str.chars().filter(c -> 'a' <= c && c <= 'z').count() > 0) count++;
if (str.chars().filter(c -> '0' <= c && c <= '9').count() > 0) count++;
if(str.chars().filter(c -> !('A' <= c && c <= 'Z') && !('a' <= c && c <= 'z') && !('0' <= c && c <= '9') && c != ' ' && c != '\n').count() > 0) count++;
return count >= 3;
}
}