题解 | #密码验证合格程序#
密码验证合格程序
http://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
密码要求:
1.长度超过8位
2.包括大小写字母.数字.其它符号,以上四种至少三种
3.不能有长度大于2的不含公共元素的子串重复 (注:其他符号不含空格或换行)
数据范围:输入的字符串长度满足 1 \le n \le 100 \1≤n≤100
思路:
1、字符串长度判断
str.length()
2、字符串字符种类限制至少有3种
遍历字符串中的字符 ,
按照种类进行设置,有记为1否则记为0
计算种类的和,小于3则不满足。
3、不能有长度大于2的且不包含公共元素的重复子串:
循环遍历字符串,取长度为3且不包含公共字符的子串,看其是否包含于后续的字符串中,若包含不满足。
package String;
import java.util.Scanner;
//HJ20 密码验证合格程序
public class PasswordCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
String in = scanner.nextLine();
System.out.println(passwdCheck(in));
}
}
public static String passwdCheck(String str){
if(str.length()<9){
return "NG";
}
// 包括大小写字母.数字.其它符号,以上四种至少三种
char[] chars = str.toCharArray();
int upperLetter = 0;
int lowLetter = 0;
int num = 0;
int other = 0;
for(char c : chars){
if('A' <=c && c<= 'Z'){
upperLetter = 1;
continue;
}
if('a' <=c && c<= 'z'){
lowLetter = 1;
continue;
}
if('0' <=c && c<= '9'){
num = 1;
continue;
}
other = 1;
}
int count = upperLetter+lowLetter+num+other;
if(count<3){
return "NG";
}
// 不能有长度大于2的不含公共元素的子串重复
//截取长度为3的子串 且 判断是否包含在 后面的子串 若是 不满足
for (int i = 0; i < str.length()-6; i++) {
String substr = str.substring(i,i+3);
//判断是否包含重复字符:
char[] subchars = substr.toCharArray();
char firstChar =subchars[0];
char secondChar =subchars[1];
char thirdChar =subchars[2];
// 不含公共元素的子串
if(firstChar == secondChar || firstChar==thirdChar || secondChar==thirdChar){
continue;
}
String behindSubStr = str.substring(i+3);
if(behindSubStr.contains(substr)){
return "NG";
}
}
return "OK";
}
}
美的集团公司福利 878人发布