[LeetCode83]Restore IP Addresses

本文介绍了一种通过递归方式将数字字符串恢复为所有可能的有效IP地址组合的算法。使用Java和C++实现,该算法将输入的数字串分为四个部分,确保每一部分都在0到255之间,并排除无效的数字组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

Analysis:

递归的将数字串分成四个部分,每个部分满足0<=p<=255。要注意一些边界case,比如010是没有意思的,“0.10.010.1”。

Java

public class Solution {
    public List<String> restoreIpAddresses(String s) {
		List<String> res = getIPAdd(s,4);
		if(res == null) res = new ArrayList<>();
		return res;
	}
	public ArrayList<String> getIPAdd(String s, int k){
		assert(k<=4 && k>=1);
		if(s==null || s.length()<k || s.length()>3*k) return null;
		ArrayList<String> res = new ArrayList<>();
		for(int i=0;i<Math.min(s.length(), 3);i++){
			String num = s.substring(0, i+1);
			if((i==0 || num.charAt(0)>'0')&& Integer.parseInt(num)<=255){
				if(k==1){
					if(i==s.length()-1)
						res.add(num);
				}else {
					ArrayList<String> remain = getIPAdd(s.substring(i+1), k-1);
					if(remain!=null){
						for(String r:remain){
							String temp = num+'.'+r;
							res.add(temp);
						}
					}
				}
			}else
				break;
		}
		return res;
	}
}
c++

class Solution {
public:
    /*
s -- string, input
start -- startindex, start from which index in s
step -- step current step index, start from 0, valid value1-4,4 means the end
ip -- intermediate, split result in current spliting process
result -- save all possible ip address
*/
void dfsIp(string s, size_t start, size_t step, string ip,
           vector<string> &result){
    if(start == s.size() && step == 4){//find a possible result
        ip.resize(ip.size()-1);
        result.push_back(ip);
        return;
    }
    //since each part of IP address is in 0..255,the leagth of each
    // part is less than 3 and more than 0
    if(s.size()-start > (4-step)*3) return;
    if(s.size()-start < (4-step)) return;

    int num=0;
    for(size_t i=start;i<start+3;i++){
        num = num*10 + (s[i]-'0');
        if(num<=255){
            ip+=s[i];
            dfsIp(s,i+1,step+1,ip+'.',result);
        }
        if(num == 0) break;
    }
}
vector<string> restoreIpAddresses(string s) {
    vector<string> result;
    string ip; // save temporaty result in processing
    dfsIp(s,0,0,ip,result);
    return result;
}
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值