题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class LegalIP {
private:
string s;
public:
//构造函数
LegalIP(const string s);
//析构函数
~LegalIP();
//判断IP地址合法性
const bool judge(void)const;
//判断字符串是否是0-255的无符号十进制数
const bool judgeNum(const string s)const;
//输出结果
void print(void)const;
};
LegalIP::LegalIP(const string s) {
this->s = s;
return;
}
LegalIP::~LegalIP() {
}
const bool LegalIP::judge(void) const {
//以开始、结束和‘.’为分界点,判断子串是否是0-255的无符号整数
string sub;
//记录开始和结束的下标
int b = 0, e = 0;
for (int i = 0; i < 4; i++) {
if (i < 3) {
for (e = b; this->s[e] != '.'; e++)
if (e >= this->s.size())
return false;
} else
for (e = b; e < this->s.size(); e++);
//避免没出现数字
if (b == e)
return false;
sub = this->s.substr(b, e - b);
if (!this->judgeNum(sub))
return false;
b = e + 1;
}
return true;
}
const bool LegalIP::judgeNum(const string s) const {
int a = atoi(s.c_str());
if ((a < 0) || (a > 255))
return false;
if ((s[0] < '1') || (s[0] > '9'))
if (a != 0)
return false;
//避免出现多余数字
for (char ch : s)
if (ch == '.')
return false;
return true;
}
void LegalIP::print(void) const {
if (this->judge())
cout << "YES" << endl;
else
cout << "NO" << endl;
return;
}
int main() {
string a;
while (cin >> a) { // 注意 while 处理多个 case
LegalIP(a).print();
}
}
// 64 位输出请用 printf("%lld")