题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static final String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String ip = sc.next(); Matcher matcher = Pattern.compile(regex).matcher(ip); if (matcher.matches()) { String[] arr = ip.split("\\."); for (String s : arr) { if (s.length() > 1 && s.startsWith("0")) { System.out.println("NO"); return; } int digit = Integer.parseInt(s); if (digit < 0 || digit > 255) { System.out.println("NO"); return; } } } else { System.out.println("NO"); return; } System.out.println("YES"); } }