题解 | #合法IP# 输入不保证正确,只能逐项判断
合法IP
http://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <bits/stdc++.h> using namespace::std;
int main() {
string str;
while (getline(cin, str)) {
vector<string> vec;
stringstream ss(str);
string tmp;
int flag = 1;
while (getline(ss, tmp, '.')) {
vec.push_back(tmp);
}
if (vec.size() != 4) {
cout << "NO" << endl;
} else {
for (int i = 0; i < str.size();i++) {
if ((str[i] != '.') && !isdigit(str[i])) {
flag = 0;
break;
}
}
for (auto const &v : vec) {
if (v.empty()) {
flag = 0;
break;
} else if (stoi(v) > 255) {
flag = 0;
break;
} else if ((v.size() > 1) && ('0' == v[0])) {
flag = 0;
break;
}
}
if (flag) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
}
return 0;
}