【LeetCode】 93. Restore IP Addresses 复原IP地址(Medium)(JAVA)

【LeetCode】 93. Restore IP Addresses 复原IP地址(Medium)(JAVA)

题目地址: https://leetcode.com/problems/restore-ip-addresses/

题目描述:

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

题目大意

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

解题方法

采用递归不断拼接 IP 地址
note: 需要注意的是 0 开头的地址,后面不能再跟数字(即 xx.011.xx.xx 这种地址不符合规范)

class Solution {
    public List<String> res = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        rH(s, new StringBuilder(), 0, 4);
        return res;
    }

    public void rH(String s, StringBuilder sb, int index, int count) {
        if (count == 0 && index < s.length()) return;
        if (count == 0 && index >= s.length()) {
            res.add(sb.toString());
            return;
        }
        if (index >= s.length()) return;
        int sum = 0;
        for (int i = index; i < s.length(); i++) {
            sum = sum * 10 + s.charAt(i) - '0';
            if (sum > 255 || (i > index && s.charAt(index) == '0')) break;
            StringBuilder temp = new StringBuilder(sb);
            temp = temp.length() == 0 ? temp.append(sum) : temp.append(".").append(sum);
            rH(s, temp, i + 1, count - 1);
        }
    }
}

执行用时 : 3 ms, 在所有 Java 提交中击败了 85.81% 的用户
内存消耗 : 39.8 MB, 在所有 Java 提交中击败了 6.67% 的用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/105565205
今日推荐