LeetCode 93 Restore IP Addresses (dfs)

244 篇文章 0 订阅
16 篇文章 0 订阅

valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245""192.168.1.312" and "192.168@1.1" are invalid IP addresses.

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

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 = "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 <= 20
  • s consists of digits only.

题目链接:https://leetcode.com/problems/restore-ip-addresses/

题目大意:给一些数字字符串,求从中可以提取出多少合法的ip地址

题目分析:dfs即可

2ms,时间击败87%

class Solution {
    
    List<String> ans;
    
    public void dfs(char[] s, int pos, int n, int cnt, int[] cur) {
        if (cnt == 4) {
            if (pos == n) {
                StringBuffer sb = new StringBuffer("");
                for (int i = 0; i < cnt - 1; i++) {
                    sb.append(cur[i]).append(".");
                }
                sb.append(cur[3]);
                ans.add(sb.toString());   
            }
            return;
        }
        if (pos >= n) {
            return;
        }
        if (s[pos] == '0') {
            cur[cnt] = 0;
            dfs(s, pos + 1, n, cnt + 1, cur);
            return;
        }
        int num = 0;
        for (int i = pos; i < Math.min(pos + 3, n); i++) {
            num = num * 10 + (s[i] - '0');
            if (num > 0 && num < 256) {
                cur[cnt] = num;
                dfs(s, i + 1, n, cnt + 1, cur);
            }
        }
    }
    
    public List<String> restoreIpAddresses(String s) {
        char[] str = s.toCharArray();
        ans = new ArrayList<>();
        dfs(str, 0, str.length, 0, new int[4]);
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值