​468. 验证IP地址​​(模拟)

分类模拟。

写的好丑。

class Solution {
public:
bool isnumber(string s){
// cout<
if(s.size()>3) return false;
for(auto ch:s) if(!isdigit(ch)) return false;
int x = stoi(s);
// printf("x=%d\n",x);
int len = 0;
int y = x;
while(y>0){
y/=10;
len++;
}
if(!x) len = 1;
if(len==s.size() && x>=0&&x<=255) return true;
return false;
}
bool myalpha(char ch){
return (ch>='a'&&ch<='f') || (ch>='A'&&ch<='F');
}
bool isnumber1(string s){
// cout<
int ls = (int)s.size();
if(ls<1 ||ls >4) return false;
for(auto ch:s) if(!isdigit(ch) && !myalpha(ch)) return false;
return true;
}
bool f1(string s){
int c = 0;
vector<int>a;
for(int i=0;i<s.size();i++){
if(s[i]=='.') a.push_back(i),c++;
}
if(c!=3) return false;
int l = 0;
a.push_back((int)s.size());
//printf("c=%d\n",c);
for(int i=0;i<4;i++){

int r = a[i]-1;
//printf("(%d,%d)\n",l,r);
if(l<=r && isnumber(s.substr(l,r-l+1))){
;
}
else return false;
l = a[i]+1;
}
return true;
}
bool f2(string s){
int c = 0;
vector<int>a;
for(int i=0;i<s.size();i++){
if(s[i]==':') a.push_back(i),c++;
}
if(c!=7) return false;
int l = 0;
a.push_back((int)s.size());
//printf("c=%d\n",c);
for(int i=0;i<8;i++){

int r = a[i]-1;
//printf("(%d,%d)\n",l,r);
if(l<=r && isnumber1(s.substr(l,r-l+1))){
;
}
else return false;
l = a[i]+1;
}
return true;
}
string validIPAddress(string s) {
if(f1(s)) return "IPv4";
else if(f2(s)) return "IPv6";
else return "Neither";
}
};