zoukankan      html  css  js  c++  java
  • Java for LeetCode 093 Restore IP Addresses

    Given a string containing only digits, restore it by returning all possible valid IP address combinations.

    For example:
    Given "25525511135",

    return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

    解题思路:

    使用循环即可解决,JAVA实现如下:

    	static public List<String> restoreIpAddresses(String s) {
    		List<String> list = new ArrayList<String>();
    		for (int i = 0; i < 3; i++)
    			for (int j = i + 2; j < i + 5&&j<=s.length()-2; j++)
    				for (int k = j + 1; k < j + 4&&k<=s.length()-1; k++){
    						if (isValid(s.substring(0, i + 1))
    								&& isValid(s.substring(i + 1, j))
    								&& isValid(s.substring(j, k))
    								&& isValid(s.substring(k, s.length())))
    							list.add(s.substring(0, i + 1) + "."
    									+ s.substring(i + 1, j) + "."
    									+ s.substring(j, k) + "."
    									+ s.substring(k, s.length()));
    					}
    		return list;
    	}
    		public static boolean isValid(String s) {
    		if (s.length()>3)
    			return false;
    		int num = Integer.parseInt(s);
    		return num <= 255 && (num + "").equals(s);
    	}
    
  • 相关阅读:
    Python中怎么使用(冒泡排序)?
    Python中怎么定义与调用(函数)
    简易购物商城(1.0)版本
    非空即真 和 切片 处理方式
    python模块-random
    内置函数
    多维数组
    函数扩展
    文件操作扩展2
    文件操作扩展
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4518358.html
Copyright © 2011-2022 走看看