Java Solution


  • 0
    1. check whether the string contains '.' or':', pass the check work to separate check function
    2. For IPv4, check if there is 4 entry and each one should be number between 0-255
    3. For IPv6, check if there is 8 entry and each one should be valid
    public class Solution {
        public String validIPAddress(String IP) {
            if(IP.indexOf('.')>=0) return checkIPv4(IP);
            else return checkIPv6(IP);
        }
        
        public String checkIPv4(String IP){
            String[] decimal=IP.split("\\.",-1);
            if(decimal.length!=4) return "Neither";
            for(String de:decimal){
                if(!checkDecimal(de)) return "Neither";
            }
            return "IPv4";
        }
        
        public boolean checkDecimal(String de){
            long value=0;
            int len=de.length();
            if(len==0||(len>1&&de.charAt(0)=='0')) return false;
            for(int i=0;i<len;i++){
                char x=de.charAt(i);
                if(x<'0'||x>'9') return false;
                value=value*10;
                value=value+x-'0';
            }
            return value<=255;
        }
        
        public String checkIPv6(String IP){
            String[] hex=IP.split("\\:",-1);
            if(hex.length!=8) return "Neither";
            for(String h:hex){
                if(!checkHex(h)) return "Neither";
            }
            return "IPv6";
        }
        
        public boolean checkHex(String h){
            int len=h.length();
            if(len>4||len==0) return false;
            for(char x:h.toCharArray()){
                if(!((x>='0'&&x<='9')||(x>='A'&&x<='F')||(x>='a'&&x<='f'))) return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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