leetcode:Restore IP Addresses 【Java】

一、问题描述

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)

二、问题分析

1、采用递归算法;

2、详见代码注释。

三、算法代码

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<String>();
		backtrack(result, s, 0, 0, new StringBuffer());
		//去掉result中每个结果最后的.,例如[255.255.11.135., 255.255.111.35.]
		for(int i = 0; i < result.size(); i++){
			result.set(i, result.get(i).substring(0, result.get(i).length() - 1));		
		}
        return result;
    }
	public void backtrack(List<String> result, String ip, int start, int step, StringBuffer ipBuffer){
		//find a resolution
		if(start == ip.length() && step == 4){
			result.add(ipBuffer.toString());
			return;
		}
		//IP地址由四段构成,剩余字符串长度大于所有还未生成的IP段的最大有效长度的总和
		//例如,剩余字符串长度为9,已生成的IP段为255.255,还有最后2段未生成,但9>2*3
		if((ip.length() - start) > (4 - step) * 3){
			return;
		}
		//IP地址由四段构成,剩余字符串长度小于所有还未生成的IP段的最小有效长度的总和
		if((ip.length() - start) < (4 - step)){
			return;
		}
		
		int num = 0;
		for(int i = start; i < start + 3 && i < ip.length(); i++){
			num = num * 10 + Character.digit(ip.charAt(i), 10);
			if(num <= 255){
				ipBuffer.append(num);
				backtrack(result, ip, i + 1, step + 1, ipBuffer.append('.'));
				if(ipBuffer.length() >= String.valueOf(num).length() + 1){//深搜不成功时,从ipBuffer中删除当前深搜产生的中间值
					ipBuffer.delete(ipBuffer.length() - String.valueOf(num).length() - 1, ipBuffer.length());
				}
			}
			if(num == 0){
				break;
			}
		}
    }
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值