Version #2 强行写java
有一个要记住的 Integer.valueOf(String) 如果不是valid integer会有一个exception
NumberFormatException
try {
int parsedInt = Integer.parseInt(token);
if(parsedInt<0 || parsedInt>255) return false;
if(parsedInt==0 && token.charAt(0)!='0') return false;
} catch(NumberFormatException nfe) {
return false;
}
Version #1
用regex
对于判断0-255的range用的是enumerate的方法
注意escape 是//
要是match . 用//.
11.35 %
class Solution {
public String validIPAddress(String IP) {
if (IP == null) return "Neither";
String pattern4 = "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
String pattern6 = "([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4})";
if (IP.matches(pattern4)) return "IPv4";
else if (IP.matches(pattern6)) return "IPv6";
else return "Neither";
}
}
No comments:
Post a Comment