题解 | #密码验证合格程序#
密码验证合格程序
http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
1.长度超过8位:
直接判断长度 length 即可,这个点比较简单;
2.包括大小写字母.数字.其它符号,以上四种至少三种:
定义4个统计变量low 、up、num、other,针对每个字符单独判断归类,最后对4个统计变量求和判断;
3.不能有相同长度大于2的子串重复:
这个点稍微有点难度,需要结合for循环嵌套+字符串截取来判断,余下的字符串是否包含另外一部分截取的字符串。
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNextLine()){ String str = sc.nextLine(); if(checkPassword(str)){ System.out.println("OK"); } else{ System.out.println("NG"); } } } public static boolean checkPassword(String str){ // 验证1.长度是否超过8位 if(str.length() <= 8){ return false; } // 验证包括的字符种类2.包括大小写字母.数字.其它符号,以上四种至少三种 int low = 0; int up = 0; int num = 0; int other = 0; for(int i = 0; i < str.length(); i++){ char tmp = str.charAt(i); if(tmp >= 'a' && tmp <= 'z'){ low = 1; } else if(tmp >= 'A' && tmp <= 'Z'){ up = 1; } else if(tmp >= '0' && tmp <= '9'){ num = 1; } else{ other = 1; } } if(low+up+num+other < 3){ return false; } // 验证是否有长度大于2的子串重复 // 这个判断子串的方式是,将一句话截成两段,只要后面一段不包含前面那段就可以了 for(int i = 0; i < str.length(); i++){ for(int j = i+3; j < str.length(); j++){ String tmp = str.substring(i, j); if(str.substring(j).contains(tmp)){ return false; } } } // 以上false都没有出现,返回true return true; } }