Beat 81.31% Java Solution


  • 0
    J

    public class Solution {
    public String validIPAddress(String IP) {
    if (IP == null || IP.length() < 7) return "Neither";
    int len = IP.length();

        if (IP.contains(".")) {
            char[] ch = IP.toCharArray();
            int cou = 0;
            for (int i = 0; i < len; i++) {
                if (ch[i] != '.') {
                    if (ch[i] - '0' <= 9 && ch[i] - '0' >=0) {
                        if (ch[i] - '0' == 0 && i == 0 && ch[i + 1] != '.') return "Neither";
                        if (ch[i] - '0' == 0 && (i > 0 && ch[i - 1] == '.' && ch[i + 1] != '.')) return "Neither";
                        cou++;
                    } else {
                        return "Neither";
                    }
                } else {
                    if (i == len - 1)  return "Neither";
                    if (cou > 3) return "Neither";
                    if (i == 0) return "Neither";
                    if (ch[i - 1] == '.') return "Neither";
                    cou = 0;
                }
            } 
            
            if (cou > 3) return "Neither";
            String ch3[] = IP.split("\\.");
            if (ch3.length != 4) return "Neither";
            int val1 = Integer.parseInt(ch3[0]);
            int val2 = Integer.parseInt(ch3[1]);
            int val3 = Integer.parseInt(ch3[2]);
            int val4 = Integer.parseInt(ch3[3]);
            
            if (val1 <= 255 && val1 >= 0 && val2 <= 255 && val2 >= 0 && val3 <= 255 && val3 >= 0 && val4 <= 255 && val4 >= 0) {
                return "IPv4";
            } else {
                return "Neither";
            }
            
        } else if (IP.contains(":")) {
            char[] ch2 = IP.toCharArray();
            int count = 0;
            if (IP.split("\\:").length != 8) return "Neither";
            for (int i = 0; i < len; i++) {
                if (ch2[i] != ':') {
                    count++;
                    if ((ch2[i] - '0' >= 0 && ch2[i] - '0' <= 9) || (ch2[i] <= 'f' && ch2[i] >= 'a') || (ch2[i] <= 'F' && ch2[i] >= 'A'))
                        continue;
                    else
                        return "Neither";
                } else {
                    if (i == len - 1) return "Neither";
                    if (count > 4) return "Neither";
                    count = 0;
                    if (i == 0) return "Neither";
                    if (ch2[i - 1] == ':') return "Neither";
                }
            }
            
            if (count > 4)  return "Neither";
            
            return "IPv6";
        }
        
        return "Neither";
    }
    

    }


Log in to reply
 

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