# C++ 28 lines solution using istringstream and unordered_set

• ``````class Solution {
public:
if(IP.size() > 39) return "Neither";
string s = IP.substr(0, 5);
bool p4 = s.find_first_of('.') != string::npos ? true : false;
bool p6 = s.find_first_of(':') != string::npos ? true : false;
iss.str(IP);
if(p4 && !p6) return isIPv4(IP) ? "IPv4" : "Neither";
else if(!p4 && p6) return isIPv6(IP) ? "IPv6" : "Neither";
else return "Neither";
}

private:
int seg_num;
string seg;
istringstream iss;
const unordered_set<char> st = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F'};

bool isIPv4(string& IP){
seg_num = 4;
while(seg_num--){
if(!getline(iss, seg, '.')) return false;
int n = seg.size();
if(!n || n > 3) return false;
for(auto& c : seg)
if(!isdigit(c)) return false;
int num = stoi(seg);
if((seg.size() > 1 && seg[0] == '0') || num < 0 || num > 255) return false;
}
return iss.eof() ? true : false;
}

bool isIPv6(string& IP){
seg_num = 8;
while(seg_num--){
if(!getline(iss, seg, ':') || !seg.size() || seg.size() > 4) return false;
for(auto& c : seg)
if(!st.count(c)) return false;
}
return iss.eof() ? true : false;
}
};

``````

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