Java naive O(n) solution just use loops


  • 0
    public String validIPAddress(String IP) {
        int len = IP.length();
        String nah = new String("Neither");
        if(len<7) return nah;
        char[] IParr = IP.toCharArray();
        int type = 0;//4 mean v4, 6 means v6.
    
        //first need to tell ipv4 or ipv6 using a small loop
        for(int i = 0;i<6;i++){
            if(IParr[i]=='.'){
                if(i<4){
                    type = 4;
                    break;
                }
                else{
                    return nah;
                }
            }
            if(IParr[i]==':'){
                type = 6;
                break;
            }
        }
        if(type == 0){//check type again if still 0 return neither
            return nah;
        }
        //isIPv4?
        if(type == 4) {
            int i = 0;
            int last = 0;
            boolean lastzero = false;
            boolean lastdot = false;
            int count = 1;
            while(i<len){
                if(IParr[i]!='.'&&(IParr[i]<'0'||IParr[i]>'9')) return nah;
                if(IParr[i]=='.'){
                    if(lastdot==true||i==len-1) return nah;
                    lastdot = true;
                    lastzero = false;
                    last = 0;
                    count++;
                }
                else{
                    if(count>4||lastzero==true) return nah;//check if '.' has divided the string into more than 4 sections or the last digit of current part is zero.
                    lastdot = false;
                    if(IParr[i]=='0') lastzero = true;
                    last = last*10 + (IParr[i] - '0');
                    if(last>255) return nah;
                }
                i++;
            }
            if(count!=4) return nah; //check # of parts again
            return new String("IPv4");
        }
        //isIPv6?
        if(type == 6) {
            int i = 0;
            int MAXLEN = 4;
            int currlen = 0;
            int count = 1;
            boolean lastcolon = false;
            while(i<len){
                if(IParr[i]!=':'&&(IParr[i]<'0'||IParr[i]>'9')&&
                    (IParr[i]<'a'||IParr[i]>'f')&&(IParr[i]<'A'||IParr[i]>'F')) return nah;//if current char valid in ipv6?
                if(IParr[i]==':'){
                    if(lastcolon==true||i==len-1) return nah;
                    currlen = 0;
                    lastcolon = true;
                    count++;
                }
                else{
                    currlen++;
                    lastcolon = false;
                    if(currlen>MAXLEN||count>8) return nah;
                }
                i++;
            }
            if(count!=8) return nah;
            return new String("IPv6");
            
        }
        return nah;
    }

Log in to reply
 

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