牛客華為機試HJ20
阿新 • • 發佈:2022-04-04
1. 問題描述
2. Solution
1、思路
注意重複字串的處理
2、實現
Java
package huawei.HJ020; import java.io.IOException; import java.nio.file.Paths; import java.util.Scanner; public class Main { static Scanner in; static String inputFileName = "/Users/jun/Documents/Learn/JavaLearning/NowCoder/src/huawei/HJ020/input.txt"; static { if (!"Linux".equals(System.getProperty("os.name"))) { try { in = new Scanner(Paths.get(inputFileName)); } catch (IOException e) { e.printStackTrace(); } } else { in = new Scanner(System.in); } } public static void main(String[] args) { while (in.hasNext()) { String s = in.nextLine(); System.out.println(solve(s)); } } private static String solve(String s) { // 1.長度超過8位 if (s.length() <= 8) return "NG"; // 2.包括大小寫字母.數字.其它符號,以上四種至少三種 boolean[] valid = new boolean[4]; // 大寫字母、小寫字母、數字、其他字元 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isUpperCase(c)) valid[0] = true; else if (Character.isLowerCase(c)) valid[1] = true; else if (Character.isDigit(c)) valid[2] = true; else if (!Character.isSpaceChar(c)) valid[3] = true; } int cnt = 0; for (boolean elem : valid) { if (elem) cnt++; } if (cnt < 3) return "NG"; // 3.不能有長度大於2的不含公共元素的子串重複 (注:其他符號不含空格或換行) for (int start = 3; start < s.length(); start++) { if (s.substring(start).contains(s.substring(start - 3, start))) return "NG"; } return "OK"; } }
Python
import sys if sys.platform != "linux": sys.stdin = open("input/HJ20.txt") def solve(s): if len(s) <= 8: return "NG" valid = [0] * 4 # 大寫字母、小寫字母、數字、其他符號 for c in s: if c.isupper(): valid[0] = 1 elif c.islower(): valid[1] = 1 elif c.isdigit(): valid[2] = 1 elif not c.isspace(): valid[3] = 1 if sum(valid) < 3: return "NG" for start in range(len(s) - 3): segment = s[start: start + 3] if len(s.split(segment)) >= 3: return "NG" return "OK" for line in sys.stdin: print(solve(line.strip()))