#93 Restore IP Addresses

这篇博客探讨了如何通过深度优先搜索算法从只包含数字的字符串中生成所有可能的有效IP地址。示例展示了不同输入字符串下的输出结果,并提到虽然当前实现的解决方案存在嵌套过多的问题,但博主计划在未来寻找更高效的方法。

Description

Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s. You can return them in any order.

A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single dots and cannot have leading zeros. For example, “0.1.2.201” and “192.168.1.1” are valid IP addresses and “0.011.255.245”, “192.168.1.312” and “192.168@1.1” are invalid IP addresses.

Examples

Example 1:

Input: s = “25525511135”
Output: [“255.255.11.135”,“255.255.111.35”]

Example 2:

Input: s = “0000”
Output: [“0.0.0.0”]

Example 3:

Input: s = “1111”
Output: [“1.1.1.1”]

Example 4:

Input: s = “010010”
Output: [“0.10.0.10”,“0.100.1.0”]

Example 5:

Input: s = “101023”
Output: [“1.0.10.23”,“1.0.102.3”,“10.1.0.23”,“10.10.2.3”,“101.0.2.3”]

Constraints:

0 <= s.length <= 3000
s consists of digits only.

思路

就是深搜,也没什么讲的
但其实我的思路不是最优解,嵌套有点太多了
等有空的时候再研究下时间短的方法吧orz

代码

class Solution {
    public List<String> answer;
    public void dfs(String left, String right){
        if ((left.split("\\.")).length == 5){
            if(right.length() == 0)
                answer.add(left.substring(1));
            return;
        }
        
        if (right.charAt(0) == '0'){
            dfs(left + "." + right.substring(0, 1), right.substring(1));
            return;
        }
        
        dfs(left + "." + right.substring(0, 1), right.substring(1));
        if(right.length() > 1)
            dfs(left + "." + right.substring(0, 2), right.substring(2));
        
        if (right.length() > 2 && Integer.parseInt(right.substring(0, 3)) < 256){
            dfs(left + "." + right.substring(0, 3), right.substring(3));
        }
        
    }
    public List<String> restoreIpAddresses(String s) {
        answer = new ArrayList<>();
        if(s.length() > 12)
            return answer;
        dfs("", s);
        return answer;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值