题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String str = in.nextLine(); str = str.trim(); int length = str.length(); if (length <= 8) { System.out.println("NG"); continue; } //大小写字母、数字或特殊字符 int count = 0; String other=".*[^A-Za-z0-9&&\\S]+.*"; String Up=".*[A-Z].*"; String Low=".*[a-z].*"; String num=".*[0-9].*"; if(str.matches(Up)){ count++; } if(str.matches(Low)){ count++; } if(str.matches(num)){ count++; } if(str.matches(other)){ count++; } //System.out.println(count); if (count < 3) { System.out.println("NG"); continue; } //条件3 String temp = str; int flag=0; for (int i = 0; i <= str.length()/2; i++) { //从i起截取3个字符,进行正则替换,若替换后字符串长度减少了6,输出NG String s=str.substring(i,i+3); str=str.replace(s,""); if(str.length()==length-6){ flag++; break; } //当前3个字符没有重复,继续向后判断,字符串还原 str=temp; } if(flag!=0){ System.out.println("NG"); continue; }else{ System.out.println("OK"); } } // System.out.println(); } }
找到最小条件,正则、字串截取