My Java Solution using try catch to validate


  • 0
    public class Solution {
        public String validIPAddress(String IP) {
            if(IP.contains(".")&&IsIPV4Valid(IP)) 
                return "IPv4";
             if(IP.contains(":")&&IsIPV6Valid(IP))   
             return "IPv6";
             return "Neither";
        }
        public boolean IsIPV4Valid(String ip)
        {
            if(ip.endsWith(".")) return false;
            String[] parts=ip.split("\\.");
            
             
            if(parts.length!=4) return false;
            try{
                for(int i=0;i<4;i++)
                {
                    int num=Integer.parseInt(parts[i]);
                    if(parts[i].startsWith("0")&&(parts[i].length()>1||num!=0)||parts[i].startsWith("-"))
                    {
                        return false;
                    }
                    if(num<0||num>255) 
                    {
                        return false;
                        
                    }
                }
                  return true;
            }
            catch(Exception e)
            {
                return false;
            }
          
            
        }
        public boolean IsIPV6Valid(String ip)
        {
             String[] parts=ip.split(":");
             if(ip.endsWith(":")) return false;
             if(parts.length!=8) return false;
            //  HashSet<Character> set = new HashSet<Character>();
            //  for(int i=0;i<9;i++) set.add((char)('0'+i));
            //  for(int i=0;i<5;i++) set.add((char)('A'+i));
              try{
              for(int i=0;i<8;i++)
                {
                     int num=Integer.parseInt(parts[i],16);
                    
                     if(parts[i].length()>4||parts[i].startsWith("-")) 
                         return false;
                }
                return true;
              }catch(Exception e)
              {
                  return false;
              }
        }
    }
    

Log in to reply
 

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