93. Restore IP Addresses

本文介绍了一种通过递归算法来解决字符串形式的数字恢复为有效IP地址的问题。该算法利用递归方式尝试所有可能的有效IP地址组合,并验证每个部分是否符合IP地址规范。文章提供了完整的Java代码实现。

摘要生成于 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)

Subscribe to see which companies asked this question.


Solution:

Tips:

recursion, check the validation of the number.


Java Code:

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList();
        if (s == null || s.length() < 4 || s.length() > 12) {
            return result;
        }
        
        restoreIpAddresses(s, 0, "", 4, result);
        
        return result;
    }
    
    public void restoreIpAddresses(String s, int begin, String curS, int ceil, List<String> result) {
        //System.out.println("s = " + s + ", begin = " + begin + ", current s = " + curS + ", ceil = " + ceil);
        if (begin > s.length() 
            || s.length() - begin < ceil 
            || s.length() - begin > ceil * 3) {
            return;
        }
        
        if (ceil == 0) {
            result.add(curS.substring(0, curS.length() - 1));
            return;
        }
        
        // cut one char
        restoreIpAddresses(s, begin + 1, curS + s.substring(begin, begin + 1) + ".", ceil - 1, result);
        if (s.charAt(begin) != '0' && begin + 1 < s.length()) {
            restoreIpAddresses(s, begin + 2, curS + s.substring(begin, begin + 2) + ".", ceil - 1, result);
            if (begin + 2 < s.length() && Integer.valueOf(s.substring(begin, begin + 3)) <= 255) {
                restoreIpAddresses(s, begin + 3, curS + s.substring(begin, begin + 3) + ".", ceil - 1, result);
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值