题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <cctype>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool check_(string s){
for (auto ch : s){
if (!isdigit(ch))
return false;
}
int num_index = 0;
if (s.size() > 1){
for (auto ch : s){
if (ch == '0' && num_index == 0)
return false;
if (ch != '0')
num_index = 1;
}
}
int x = stoi(s);
if (x < 0 || x > 255)
return false;
return true;
}
int main() {
string str;
while (cin>>str){
vector<string> vec;
string tmp;
for (int i = 0; i < str.size(); i++){
if (i == str.size() - 1 ){
tmp += str[i];
vec.push_back(tmp);
}
if (str[i] == '.' && !tmp.empty()){
vec.push_back(tmp);
tmp = "";
}
else {
tmp += str[i];
}
}
int index = 0;
if (vec.size() != 4){
index = 1;
}
for (auto it : vec){
if (!check_(it)){
index = 1;
}
}
if (index)
cout<<"NO";
else
cout<<"YES";
}
}
// 64 位输出请用 printf("%lld")

