【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% 的用户

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值