详见:https://leetcode.com/problems/validate-ip-address/description/
Java实现:
class Solution {
public String validIPAddress(String IP) {
if (isIpV4(IP)) {
return "IPv4";
} else if (isIpV6(IP)) {
return "IPv6";
} else {
return "Neither";
}
}
private boolean isIpV4(String ip) {
if (ip == null || ip.isEmpty()) {
return false;
}
String[] splits = ip.split("\.", -1);
if (splits.length != 4){
return false;
}
for (int i = 0; i < 4; i++) {
try {
int val = Integer.parseInt(splits[i], 10);
if (val < 0 || val > 255){
return false;
}
} catch (Exception e) {
return false;
}
if (splits[i].charAt(0) == '-' || splits[i].charAt(0) == '+'){
return false;
}
if (splits[i].charAt(0) == '0' && splits[i].length() > 1){
return false;
}
}
return true;
}
private boolean isIpV6(String ip) {
if (ip == null || ip.isEmpty()) {
return false;
}
String[] splits = ip.split(":", - 1);
if (splits.length != 8){
return false;
}
for (int i = 0; i < 8; i++) {
try {
int val = Integer.parseInt(splits[i], 16);
if (val < 0 || val > 65535){
return false;
}
} catch (Exception e) {
return false;
}
if (splits[i].charAt(0) == '-' || splits[i].charAt(0) == '+'){
return false;
}
if (splits[i].length() > 4){
return false;
}
}
return true;
}
}
C++实现:
class Solution {
public:
string validIPAddress(string IP)
{
if(IsIPv4(IP))
{
return "IPv4";
}
else if(IsIPv6(IP))
{
return "IPv6";
}
else
{
return "Neither";
}
}
private:
bool IsIPv4(string IP)
{
string temp="";
int count=0;
int count1=0;
for(int i=0;i<=IP.length();i++)
{
if(IP[i]!='.'&&IP[i]!=' ')
{
if(IP[i]<'0'||IP[i]>'9')
{
return false;
}
temp=temp+IP[i];
count1++;
if(count1>=4)
{
return false;
}
}
else
{
if(temp!=""&&stoi(temp)<256&&stoi(temp)>=0)
{
if(temp[0]=='0'&&temp.length()>1)
{
return false;
}
count++;
if(count==4)
{
return i==IP.length();
}
}
else
{
return false;
}
temp="";
count1=0;
}
}
return false;
}
bool IsIPv6(string IP)
{
string temp="";
int count=0;
int count1=0;
for(int i=0;i<=IP.length();i++)
{
if((IP[i]>='0'&&IP[i]<='9')||(IP[i]>='A'&&IP[i]<='F')||(IP[i]>='a'&&IP[i]<='f'))
{
count1++;
if(count1>4)
{
return false;
}
}
else if(IP[i]==':'||IP[i]==' ')
{
if(count1==0)
{
return false;
}
count++;
count1=0;
if(count==8)
{
return i==IP.length();
}
}
else
{
return false;
}
}
return false;
}
};
参考:https://blog.csdn.net/starstar1992/article/details/54925098