Valid IP Address

Valid IP Address

题目描述:

给定一个字符串;判断其是否是有效的IPV4或者IPV6的字符串。其中字符串不包含空格和特殊字符。

例子:

具体的例子和描述可以参考LeetCode_468

解题思路:

本题中首先主要的难点在于如何分割字符串;利用C++的stringstream函数和getline函数可以将字符串按照指定的方式进行分割;然后就是边界条件的判断,主要包括:

  • 每个分割子串长度判断,IPV4不超过3,IPV6长度不超过4
  • 当前的子串个数判断,IPV4个数为4,IPV6个数为6
  • IPV4中的首字母为0的判断
  • 子串为空的判断,IPV4和IPV6长度均不能为空
  • 子串中各个字符的判断,IPV4中只能是数字类型,IPV6的字母是16进制范围
  • 字符串结尾的判断,字符串的结尾不能是”:”和”.”

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
string validIPAddress(string IP) {
stringstream is(IP);
string tmp = "";
int count = 0;
if (IP.find(':') == string::npos){
while(getline(is, tmp, '.')){
count++;
if (tmp.empty() || tmp.size() > 3 || (tmp.size() > 1 && tmp[0] == '0') || count > 4) return "Neither";
for (char c : tmp){
if (c < '0' || c > '9')
return "Neither";
}
int val = stoi(tmp);
if (val < 0 || val > 255) return "Neither";
}
return (IP.back() != '.' && count == 4) ? "IPv4" : "Neither";
}else{
while(getline(is, tmp, ':')){
count++;
if (tmp.empty() || tmp.size() > 4 || count > 8) return "Neither";
for (char c : tmp){
if (!(c <= '9' && c >= '0') && !(c <= 'f' && c >= 'a') && !(c <= 'F' && c >= 'A'))
return "Neither";
}
}
return (count == 8 && IP.back() != ':') ? "IPv6" : "Neither";
}
}
};