题解 | #密码验证合格程序#
密码验证合格程序
http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
- 首先判断长度
- 其次判断种类
- 最后判断字串,判断字串直接遍历,不过串不是很长,还是能接受的
- 最后一步可以做一下修改,其实是没有必要循环判断的,因为只要存在长度为4的重复子串则一定存在长度为3的重复子串,所以其实只用判断长度为3的即可
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
if(checkValid(str)){
System.out.println("OK");
}else{
System.out.println("NG");
}
}
}
public static boolean checkValid(String str){
//首先判断长度是否符合要求
if(str.length() <= 8){
return false;
}
boolean hasDigit=false,hasUpperCase=false,hasLowerCase=false,hasOther=false;
int countKind = 0;
//其次判断字符种类是否符合要求
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
if(Character.isDigit(c)){
if(!hasDigit){
countKind++;
hasDigit = true;
}
}else if(Character.isUpperCase(c)){
if(!hasUpperCase){
countKind++;
hasUpperCase = true;
}
}else if(Character.isLowerCase(c)){
if(!hasLowerCase){
countKind++;
hasLowerCase = true;
}
}else if(c!=' ' && c!='\n'){
if(!hasOther){
countKind++;
hasOther = true;
}
}
}
if(countKind<3){
return false;
}
//判断字符种类符合要求之和继续判断字串是否符合要求
// 从第i个位置截取去长度为len的子串,并且在str[i+1:]上查找,找到机存在
//for(int i = 0; i < str.length(); i++){
// for(int len = 3; len < str.length()-i; len++){
// if(str.indexOf(str.substring(i, i+len), i+1)>=1){
// return false;
// }
// }
//}
for(int i = 0; i < str.length() - 3; i++){
if(str.indexOf(str.substring(i, i+3), i+1)>=1){
return false;
}
}
return true;
}
}