1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public String validIPAddress(String queryIP) { if (queryIP.contains(".") && checkIPv4(queryIP)) return "IPv4"; else if (queryIP.contains(":") && checkIPv6(queryIP)) return "IPv6"; else return "Neither"; }
private boolean checkIPv4(String ip) { char[] s = ip.toCharArray(); int n = s.length, cnt = 0; for (int i = 0; i < n && cnt < 4; ) { int j = i, x = 0; while (j < n && (s[j] >= '0' && s[j] <= '9') && x <= 255) x = x * 10 + (s[j++] - '0'); if (i == j) return false; if ((j - i > 1 && s[i] == '0') || x > 255) return false; i = j + 1; if (j == n) continue; if (s[j] != '.') return false; ++cnt; } return cnt == 3 && s[0] != '.' && s[n - 1] != '.'; }
private boolean checkIPv6(String ip) { char[] s = ip.toCharArray(); int n = s.length, cnt = 0; for (int i = 0; i < n && cnt < 8; ) { int j = i; while (j < n && ((s[j] >= 'a' && s[j] <= 'f') || (s[j] >= 'A' && s[j] <= 'F') || (s[j] >= '0' && s[j] <= '9'))) ++j; if (i == j || j - i > 4) return false; i = j + 1; if (j == n) continue; if (s[j] != ':') return false; ++cnt; } return cnt == 7 && s[0] != ':' && s[n - 1] != ':'; } }
|