题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
bool strvalid(char* str) {
int len = 0;
int dot[10]={0};
int dot_i = 0;
while (str[len]) {
if (!(str[len] =='.' || isdigit(str[len]))) return false;
if (str[len] == '.') {
dot[dot_i] = len;
dot_i++;
// printf("%d %d %d\n", len, dot_i,dot[dot_i-1]);
}
len++;
for (int i=0; i<len-1; i++) {
if(str[len] == '.' && str[len+1] == '.')return false;
}
}
//int x=str[0] == '0' && str[1] != '.';
// int x1=str[dot[0] + 1] == '0' && str[dot[0] + 2] != '.';
// int x2=str[dot[1] + 1] == '0' && str[dot[1] + 2] != '.';
// int x3=str[dot[2] + 1] == '0' && dot[2] != len-2;
// int x4=dot_i != 3;
// printf("x=%d %d %d %d %d\n",x,x1,x2,x3,x4);
if ((str[0] == '0' && str[1] != '.')
|| (str[dot[0] + 1] == '0' && str[dot[0] + 2] != '.')
|| (str[dot[1] + 1] == '0' && str[dot[1] + 2] != '.')
|| (str[dot[2] + 1] == '0' && dot[2] != len-2)
|| dot_i != 3) {
// printf("f2");
return false;
}
return true;
}
bool numvalid(char* str) {
int a, b, c, d;
sscanf(str, "%d.%d.%d.%d", &a, &b, &c, &d);
if ((a >= 0 && a < 256) && (b >= 0 && b < 256) && (c >= 0 && c < 256) &&
(d >= 0 && d < 256))return true;
//printf("f3");
return false;
}
int main() {
char str[100];
while (~scanf("%s", str)) {
printf("%s\n", strvalid(str) && numvalid(str) ? "YES" : "NO");
}
}
格式可真恶心,,一遍遍调吧。。。笨方法
