题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.util.*;
import java.util.regex.Pattern;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static boolean isMatch(String str){ //满足正则返回false
int index = 0;
Pattern p1 = Pattern.compile("[^a-zA-Z0-9]");
if(p1.matcher(str).find()){
index++;
}
Pattern p2 = Pattern.compile("[a-z]");
if(p2.matcher(str).find()){
index++;
}
Pattern p3 = Pattern.compile("[0-9]");
if(p3.matcher(str).find()){
index++;
}
Pattern p4 = Pattern.compile("[A-Z]");
if(p4.matcher(str).find()){
index++;
}
if(index >= 3){
return false;
}else{
return true;
}
}
public static boolean isSame(String str,int l,int r){
if(r > str.length()){
return false;
}
if(str.substring(r).contains(str.substring(l,r))) {
return true;
}else{
return isSame(str,l+1,r+1);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String str = in.nextLine();
if(str.length() <= 8){
System.out.println("NG");
continue;
}
if(isMatch(str)){
System.out.println("NG");
continue;
}
if(isSame(str,0,3)){
System.out.println("NG");
continue;
}
System.out.println("OK");
}
}
}
思路
总体考察字符串操作,要求2:用正则既可,要求3:用String的.substring()判断有无重复既可
总结
1.
Pattern p1 = Pattern.compile("[^a-zA-Z0-9]");
if(p1.matcher(str).find()){
……;
}
Pattern p1 = Pattern.compile("[^a-zA-Z0-9]");:这一行代码创建了一个正则表达式模式对象 p1,用于匹配任何字符。
p1.matcher(str):这一部分使用上面创建的正则表达式模式对象 p1 来创建一个匹配器对象,该匹配器用于在字符串 str 中进行匹配操作。
find():这是一个 Matcher 类的方法,用于在输入的字符串中查找与模式匹配的子序列。如果找到匹配项,则返回 true;否则返回 false。
总之,这段代码意思是:把正则表达式用Pattern.compile()存着,然后把正则放到字符串str中找,找到就true,一点都找不到就返回false。
2.
public static boolean isSame(String str,int l,int r){
……
if(str.substring(r).contains(str.substring(l,r))) {
return true;
}else{
return isSame(str,l+1,r+1);
}
}
这段代码中思维挺巧(不愧是大佬的思维),用递归来找有无重复
李咸鱼刷题小结 文章被收录于专栏
总结一下我的刷题过程、错误以及学到的知识

美团成长空间 2663人发布