Java Clear Sln with same pattern on IPv4 & IPv6


  • 0
    Y

    '''

    public String validIPAddress(String IP) {
        int dot = IP.indexOf('.'),
            colon = IP.indexOf(':');
            
        if ( !(dot!=-1 ^ colon!=-1) )
            return "Neither";
        else if (dot!=-1 && isIPv4(IP))
            return "IPv4";
        else if (isIPv6(IP))
            return "IPv6";
        
        return "Neither";    
    }
    
    boolean isIPv4(String s){
        int spCnt = 0;
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if ('0'<=c && c<='9')
                sb.append(c);
            else if (c=='.')
                spCnt++;
            else
                return false;
            
            if (c=='.' || i==s.length()-1){
                if (sb.length() > 3 || sb.length()>1 && sb.charAt(0)=='0' ||
                    Integer.valueOf(sb.toString()) > 255 )
                    return false;
                sb.setLength(0);
            }
        }
        return spCnt==3;
    }
    
    boolean isIPv6(String s){
        int spCnt = 0;
        int tokenLen = 0;
        for (int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if ('0'<=c && c<='9' || 'a'<=c && c<='f' || 'A'<=c && c<='F')
                tokenLen++;
            else if (c==':')
                spCnt++;
            else
                return false;
            
            if (c==':' || i==s.length()-1){
                if (tokenLen < 1 || tokenLen > 4)
                    return false;
                tokenLen = 0;
            }
        }
        return spCnt==7;
    }
    

    '''


Log in to reply
 

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