题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; while((str = br.readLine()) != null) { String flag = "YES"; if(str.length() - str.replaceAll("[^0-9\\.]+", "").length()> 0) { flag = "NO"; } String[] arr = str.replaceAll("[^0-9\\.]+", "").split("\\."); if(arr.length != 4) { flag = "NO"; } for (int i = 0; i < arr.length; i++) { if(arr[i].length() == 0) { flag = "NO";break; } //==""依然报错 if(arr[i].startsWith("0") && arr[i].length() > 1) { flag = "NO";break; } int k =Integer.parseInt(arr[i]); if(k>255 || k< 0) { flag = "NO";break; } } System.out.println(flag); } } }