题解 | #验证IP地址#使用状态机思路
验证IP地址
http://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
这个题做死我了
class Solution {
public:
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
auto isv4(string const& segement) -> bool {
if (segement.empty()) return false;
if (segement[0] == '0' && segement.length() > 1) return false;
auto cur{0};
for (auto ch : segement) {
if (!isdigit(ch)) return false;
cur = 10 * cur + (ch - '0');
}
return cur <= 0xff;
}
auto isv6(string const& segement) -> bool {
if (segement.empty()) return false;
if (segement.length() > 4) return false;
if (segement.length() > 1 && segement.front() == '0' && segement[1] == '0') return false;
auto cur{0};
for (auto ch : segement) {
if (isdigit(ch)) {
cur = 16 * cur + (ch - '0');
}else {
ch = tolower(ch);
cur = 16 * cur + (ch - 'a' + 10);
}
}
return cur <= 0xffff;
}
string solve(string ip) {
// write code here
string ans;
auto seg4{0}, seg6{0};
enum Statu{alnum, other} statu{other};
enum Type{v4, v6} type;
size_t start{0};
for (size_t i = 0; i < ip.length(); ++i) {
if (auto ch = ip[i]; isalnum(ch)) {
if (statu == other) {
start = i;
statu = alnum;
}
if (i == ip.length() - 1) {
if (type == v4) {
++seg4;
if (!isv4(ip.substr(start))) {
ans = "Neither";
}
}else if (type = v6) {
++seg6;
if (!isv6(ip.substr(start))) {
ans = "Neither";
}
}
}
}else {
if (statu == alnum) {
statu = other;
if (ch == '.') {
type = v4;
ans = "IPv4";
++seg4;
if (!isv4(ip.substr(start, i - start))) {
ans = "Neither";
break;
}
}else if (ch == ':') {
type = v6;
ans = "IPv6";
++seg6;
if (!isv6(ip.substr(start, i - start))) {
ans = "Neither";
break;
}
}
}
}
}
if (statu == other) ans = "Neither";
if (type == v4 && seg4 != 4) ans = "Neither";
if (type == v6 && seg6 != 8) ans = "Neither";
return ans;
}
};