LeetCode每日一题:恢复ip地址

问题描述

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)

问题分析

把字符串分解成符合规定的ip地址,首先要明白ip地址的性质

  • ip地址分为四节,每节取值范围在[0,255]
  • 对于取出的字符串,若它的第一位为’0’,那么它的长度只能为1,多位字符不能以0作为开头

明白这两点,我们可以每次拿出[1,3]个字符,判断是否符合ip地址的条件,若符合,则递归剩下的字符串,直到四节都符合,那么就得到了一个解,这是分治算法思想

代码实现

public ArrayList restoreIpAddresses(String s) {
        ArrayList result = new ArrayList<>();
        if (s.length() > 12 || s.length() == 0) return result;
        getIpAddresses(s, 0, "", result);
        return result;
    }

    private void getIpAddresses(String input, int position, String ipAddress, ArrayList result) {
        if (input.length() == 0) return;
        if (position == 3) {//只能存在四节ip
            int num = Integer.parseInt(input);
            if (input.charAt(0) == '0') {
                if ((input.length() == 1 && num == 0) == false) return;
            }
            if (num <= 255) {
                ipAddress = ipAddress + input;
                result.add(ipAddress);
                return;
            }
        } else {
            if (input.length() >= 1) {
                getIpAddresses(input.substring(1), position + 1,
                        ipAddress + input.substring(0, 1) + ".", result);
            }
            if (input.length() >= 2 && input.charAt(0) != '0') {
                getIpAddresses(input.substring(2), position + 1,
                        ipAddress + input.substring(0, 2) + ".", result);
            }
            if (input.length() >= 3 && input.charAt(0) != '0') {
                int num = Integer.parseInt(input.substring(0, 3));
                if (num <= 255) {
                    getIpAddresses(input.substring(3), position + 1,
                            ipAddress + input.substring(0, 3) + ".", result);
                }
            }
        }
    }

你可能感兴趣的:(LeetCode每日一题:恢复ip地址)