Jan 24 - Restore Ip Addresses; BackTracking; Recursion; DFS;

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jan 24 - Restore Ip Addresses; BackTracking; Recursion; DFS;相关的知识,希望对你有一定的参考价值。

 

Code:

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> list = new ArrayList<>();
        int len = s.length();
        if(len < 4) return list;
        String ip = "";
        validIpAddresses(s, ip, 4, len, 0, list);
        return list;
    }
    
    public void validIpAddresses(String s, String ip, int n, int len, int pos, List<String> list){
        int size = len - pos;
        if(size <= 0) return;
        if(n == 1){
            if(size > 3) return;
            String block = s.substring(pos, pos+size);
            if(Integer.parseInt(block) > 255) return;
            if(size > 1 && s.charAt(pos) == ‘0‘) return;
            ip = ip + block;
            list.add(ip);
            return;
        }
        if(size > 3) size = 3;
        for(int i = 1; i <= size; i++){
            String block = s.substring(pos, pos+i);
            if(i > 1 && s.charAt(pos) == ‘0‘) return;
            if(Integer.parseInt(block) > 255) return;
            validIpAddresses(s, ip + block +".", n-1, len, pos+i, list);
        }
    }
}

 

以上是关于Jan 24 - Restore Ip Addresses; BackTracking; Recursion; DFS;的主要内容,如果未能解决你的问题,请参考以下文章

Linux 命令(217)—— iptables-restore 命令

Restore IP Addresses

93. Restore IP Addresses

93. Restore IP Addresses 93.恢复IP地址

[LeetCode] Restore IP Addresses 复原IP地址

[Leetcode] restore ip address 存储IP地址