leetcode: Restore IP Addresses

本文介绍了一种通过递归遍历所有可能情况来恢复IP地址的算法实现。着重讲解了如何确保每段IP地址不超过255且符合IP地址的规范格式。通过具体的Java代码示例,展示了算法的具体实现细节。

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

还是递归遍历所有可能的情况....

需要注意:

1. ip一共四块,每一块不能大于255

2. 当当前块为0时,这一块就只能为0(因为不可能出现1.1.010.1这样的ip地址),其余的两个方向(当前块继续增加)

3. 根据当前是第几块来判断“.”的添加....



public class Solution {
    List<String> res;
    public List<String> restoreIpAddresses(String s) {
        res=new ArrayList<String>();
        fun( s,0,-1,"",0 );
        return res;
    }
    void fun( String s,int index,int num,String str,int bits )
    {
        if( num>255 )
        {
            return ;
        }
        if( bits>4 )
        {
            return ;
        }
        if( index>=s.length() )
        {
            if( bits==3&&num!=-1)
            {
                str+="."+num;
                res.add(str);
            }
            return ;
        }
        if( num!=-1 )
        {
            String tmp=str;
            if( bits==0 )
            {
                tmp+=num;
            }
            else
            {
                tmp+="."+num;
            }
            fun( s,index+1,s.charAt(index)-'0',tmp,bits+1);
            if( num==0 )
            {
                return ;
            }
        }
        if( num==-1 )
        {
            num=s.charAt(index)-'0';
        }
        else
        {
            num=num*10+s.charAt(index)-'0';
        }
        fun( s,index+1,num,str,bits);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值