[算法]验证IP地址——LeetCode.468

题目链接   啊,这可能是我做过的算是数一数二恶心的了,要考虑的情况有多种,在你wa之前你永远不知道有多么恶心的样例在等着你

思路

判断一个所给字符串是否满足IPV4或IPV6,(没有0压缩还算是手下留情了),字符串分别按“.”与“:”切边然后按条件判断即可

踩过的坑。。。

题解代码

完整带测试代码

package com.leaf;

import java.math.BigInteger;

public class ValidIPAddress {

	public static void main(String[] args) {
		System.out.println(validIPAddress("192.0.0.1"));
	}
	
	public static String validIPAddress(String IP) {
		int fin = IP.length()-1;
		if(fin==-1) {
			return "Neither";
		}
		
		if(IP.charAt(0)==':'||IP.charAt(0)=='.'||IP.charAt(fin)==':'||IP.charAt(fin)=='.') {
			return "Neither";
		}
		
		
		if(IP.contains(".")) {
			
			String te[] = IP.split("\\.");	//注意此处转义
			
			if(te.length!=4) {
				return "Neither";
			}
			
			for(int i=0;i<4;i++) { if(te[i].equals("")) { return "Neither"; } if(te[i].charAt(0)=='0'&&te[i].length()>1) {
					return "Neither";
				}
				
				String regex1 = ".*[a-zA-Z].*";  
				if(te[i].matches(regex1)) {
					return "Neither";
				}
				
				BigInteger ter = new BigInteger(te[i]);
				BigInteger max = new BigInteger("255");
				BigInteger min = new BigInteger("0");
				
				if(ter.compareTo(max)==1||ter.compareTo(min)==-1) {
					return "Neither";
				}
			}
		return "IPv4";
			
		}
		
		if(IP.contains(":")) {
			String te[] = IP.split(":");
			
			if(te.length!=8) {
				return "Neither";
			}
			
			for(int i=0;i<8;i++) { if(te[i].length()>=5) {
					return "Neither";
				}
				if(te[i].equals("")) {
					return "Neither";
				}
				for(int j=0;j<te[i].length();j++) {
					String regex1 = ".*[g-zG-Z].*";
					if(te[i].matches(regex1)) {
						return "Neither";
					}
				}
				
				
			}
			
			return "IPv6";
			
		}else {
			return "Neither";
		}

    }
	
}

心得

  1. 注意所给字符串可能为空,可能以"."或":"开头的情况
  2. 注意用"."划分字符串时要转义("\\.")
  3. 正则表达式匹配字符串中是否含字母的形式:String regex1 = ".*[a-zA-Z].*";  
  4. 两个大数对象之间判断大小使用compareTo()方法(视情况会返回-1,0,1)
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注