Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
validate-ip-address.cpp 1.53 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-12-20 14:57 +08:00 . Create validate-ip-address.cpp
// Time: O(1)
// Space: O(1)
class Solution {
public:
string validIPAddress(string IP) {
stringstream ss(IP);
string block;
if (IP.substr(0, 4).find('.') != string::npos) {
for (int i = 0; i < 4; ++i) {
if (!getline(ss, block, '.') || !isValidIPv4Block(block)) {
return "Neither";
}
}
if (ss.eof()) {
return "IPv4";
}
} else if (IP.substr(0, 5).find(':') != string::npos) {
for (int i = 0; i < 8; ++i) {
if (!getline(ss, block, ':') || !isValidIPv6Block(block)) {
return "Neither";
}
}
if (ss.eof()) {
return "IPv6";
}
}
return "Neither";
}
private:
bool isValidIPv4Block(const string& block) {
int num = 0;
if (block.size() > 0 && block.size() <= 3) {
for (int i = 0; i < block.size(); ++i) {
char c = block[i];
if (!isalnum(c) || (i == 0 && c == '0' && block.size() > 1)) {
return false;
} else {
num *= 10;
num += c - '0';
}
}
return num <= 255;
}
return false;
}
bool isValidIPv6Block(const string& block) {
if (block.size() > 0 && block.size() <= 4) {
for (int i = 0; i < block.size(); ++i) {
char c = block[i];
if (!isxdigit(c)) {
return false;
}
}
return true;
}
return false;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助