468. 验证IP地址 - 力扣(LeetCode)
emmm…
这个题很烦,基本就是面向测试用例编程。。。
class Solution {
public:
int check(string& s, char a){
int cnt = 0;
if(a == '.'){// ipv4判断,cnt统计'.'出现次数
for(auto c: s){
if(c == a) ++cnt;
else if(!isdigit(c)) return 0;//不是数字也不是'.'
}
}else{//ipv6, cnt统计出现':'的次数
for(auto c: s){
if(c == a) ++cnt;
else if(!(isdigit(c) || (isalpha(c) && 'A' <= toupper(c) && toupper(c) < 'G'))) return 0;
}
}
return cnt;
}
string validIPAddress(string IP) {
if(IP.find(".") != string::npos) return judgeV4(IP);
return judgeV6(IP);
}
string judgeV4(string ip){
if(check(ip, '.') != 3) return "Neither";
int cnt = 0;
stringstream ss(ip);
string tmp;
//getline 可以用指定的分隔符来分割流中的数据
while(getline(ss, tmp, '.')){
++cnt;
if(tmp.empty() || tmp.size() > 3) return "Neither";
if(tmp.size() > 1 && (tmp[0] < '1' || tmp[0] > '9')) return "Neither";//多位数的第一位数必须合法
if(stoi(tmp) > 255) return "Neither";
}
return cnt == 4? "IPv4": "Neither";
}
string judgeV6(string ip){
if(check(ip, ':') != 7) return "Neither";
stringstream ss(ip);
int cnt = 0;
string tmp;
while(getline(ss, tmp, ':')){
++cnt;
if(tmp.empty() || tmp.size() > 4) return "Neither";
}
return cnt == 8 ? "IPv6" : "Neither";
}
};