[LeetCode 93] Restore IP Addresses

题目链接:restore-ip-addresses


import java.util.ArrayList;
import java.util.List;

/**
 * 
		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)

 *
 */

public class RestoreIPAddresses {
	
//	147 / 147 test cases passed.
//	Status: Accepted
//	Runtime: 236 ms
//	Submitted: 0 minutes ago
	//回溯法
	//时间复杂度O(n ^ 4) 空间复杂度O(n)
	public List<String> ips = new ArrayList<String>();
    public List<String> restoreIpAddresses(String s) {
        restoreIpAddresses(s, 0, "", 0);
    	return ips;
    }
    
    /**
     * 
     * @param s			原始ip字符串
     * @param cur		原始ip字符串的游标,表示当前从哪开始取数
     * @param ip		已经生成的ip的中间值
     * @param count		纪录已经生成的点位个数
     */
    public void restoreIpAddresses(String s, int cur, String ip, int count) {
    	if(s.length() > 16) {
    		return;
    	}
    	if(count == 4 && cur < s.length())
    		return;
    	if(cur == s.length()) {
			if (count == 4) {
				ips.add(ip.substring(0, ip.length() - 1));
			}
			return;
		}
    	//点分组为一位数时
		int num1 = stringToInteger(s.substring(cur, cur + 1));
		if (num1 >= 0 && num1 < 10) {
			restoreIpAddresses(s, cur + 1, ip + num1 + ".", count + 1);
		}
		//点分组为两位数时
		if (cur + 1 < s.length()) {
			int num2 = stringToInteger(s.substring(cur, cur + 2));
			if (num2 > 9 && num2 < 100) {
				restoreIpAddresses(s, cur + 2, ip + num2 + ".", count + 1);
			}
		}
		//点分组为三位数时
		if (cur + 2 < s.length()) {
			int num3 = stringToInteger(s.substring(cur, cur + 3));
			if (num3 > 99 && num3 < 256) {
				restoreIpAddresses(s, cur + 3, ip + num3 + ".", count + 1);
			}
		}
    }
    //字符转换为数值
    public int stringToInteger(String s) {
    	int n = 0;
    	for (Character digit : s.toCharArray()) {
			n = n * 10 + digit - '0';
		}
    	return n;
    }
	public static void main(String[] args) {
		System.out.println(new RestoreIPAddresses().restoreIpAddresses("25525511135"));
		System.out.println(new RestoreIPAddresses().restoreIpAddresses("1111"));

	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值