题解 | #密码强度等级#
密码强度等级
https://www.nowcoder.com/practice/52d382c2a7164767bca2064c1c9d5361
import java.util.*; import java.util.regex.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String password = in.nextLine(); System.out.print(level(password)); } } static String level(String psw) { int score = score(psw); if (score >= 90) { return "VERY_SECURE"; } if (score >= 80) { return "SECURE"; } if (score >= 70) { return "VERY_STRONG"; } if (score >= 60) { return "STRONG"; } if (score >= 50) { return "AVERAGE"; } if (score >= 25) { return "WEAK"; } return "VERY_WEAK"; } public static int score(String psw) { int length = length(psw); int letter = letter(psw); int num = num(psw); int charact = charact(psw); int reward = 0; if (letter > 0 && num > 0) { reward = Math.max(2, reward); } if (letter > 0 && num > 0 && charact > 0) { reward = Math.max(3, reward); } if (letter == 20 && num > 0 && charact > 0) { reward = Math.max(5, reward); } return length + letter + num + charact + reward; } static int length(String psw) { int length = psw.length(); if (length <= 4) { return 5; } else if (length >= 5 && length <= 7) { return 10; } else { return 25; } } static int letter(String psw) { int lower = 0; int upper = 0; Matcher l = matcher("[a-z]", psw); if (l.find()) { lower = 10; } Matcher u = matcher("[A-Z]", psw); if (u.find()) { upper = 10; } return lower + upper; } static int num(String psw) { int res = 0; Matcher matcher = matcher("[0-9]", psw); while (matcher.find()) { res = res >= 10 ? 20 : 10; } return res; } static int charact(String psw) { int res = 0; //正则表达式是用来匹配除了小写字母、大写字母、数字和中文之外的所有字符 //`^`:在方括号内,`^`表示“非”的意思,也就是除了后面的字符之外的所有字符。 Matcher matcher = matcher("[^0-9a-zA-Z\u4e00-\u9fa5]", psw); while (matcher.find()) { res = res >= 10 ? 25 : 10; } return res; } static Matcher matcher(String regex, String psw) { return Pattern.compile(regex).matcher(psw); } }