Java solution


  • 0
    A
    import java.util.*;
    
    public class Solution {
        public String validIPAddress(String IP) {
            if (isIPv4(IP)) return "IPv4";
            if (isIPv6(IP)) return "IPv6";
            return "Neither";
        }
        
        private boolean isIPv4(String s) {
            StringTokenizer tk = new StringTokenizer(s, ".");
            if (tk.countTokens()!=4) return false;
            if (s.endsWith(".")) return false;
            while (tk.hasMoreTokens()) {
                String i = tk.nextToken();
                if (i.isEmpty()) return false;
                if (i.charAt(0)=='-') return false;
                try {
                    int val = Integer.parseInt(i);
                    if (val<0 || val>255) return false;
                } catch (Exception e) {
                    return false;
                }
                if (i.length()>1 && i.charAt(0)=='0') return false;
            }
            return true;
        }
        
        private boolean isIPv6 (String s) {
           StringTokenizer tk = new StringTokenizer(s, ":");
            if (tk.countTokens()!=8) return false;
            if (s.endsWith(":")) return false;
            while (tk.hasMoreTokens()) {
                String i = tk.nextToken();
                if (i.isEmpty()) return false;
                if (i.charAt(0)=='-') return false;
                try {
                    int val = Integer.parseInt(i, 16);
                    if (val<0) return false;
                    if (i.length()>4) return false;
                } catch (Exception e) {
                    return false;
                }
            }
            return true;
        }
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.