题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <bits/stdc++.h> #include <arpa/inet.h> #include <regex> using namespace std; void process(string ip){ regex pattern("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\.){4}");//匹配0.0.0.0.-255.255.255.255.的正则表达式 ip += "."; //正则表达式匹配的四个点,ip地址后面再加一个 if(regex_match(ip, pattern)) //匹配函数 cout << "YES" << endl; else cout << "NO" << endl; } //判断ip /*判断IP地址是否合法,如果满足下列条件之一即为非法地址 数字段数不为4 存在空段,即【192..1.0】这种 某个段的数字大于255 */ //一个ip实际上是由4个[0,255] 之间的值拼接而成, 所以验证其是否都在范围内即可 bool judgeIP(string s){ int count = 0; stringstream iss(s); string tmp = ""; while(getline(iss, tmp, '.')){ if(++count > 4 || tmp.empty() || stoi(tmp) > 255 || stoi(tmp) < 0 || (tmp.size() > 1 && (tmp[0]=='0' || !isdigit(tmp[0]) )) ){ return false; } } return count == 4; } int main(){ string IP = ""; while(cin >> IP){ /*//法一 struct sockaddr_in sa; //inet_pton这个函数在成功时返回1,失败时返回0 if(inet_pton(AF_INET, IP.c_str(), &(sa.sin_addr))) cout << "YES" << endl; else cout << "NO" << endl;*/ //法二 if(judgeIP(IP)) cout << "YES" << endl; else cout << "NO" << endl; //法三 //process(IP); } return 0; }
华为题库题解 文章被收录于专栏
牛客华为题库的题解