93. Restore IP Addresses -Medium

Question

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

给出一个仅包含数字的字符串,返回所有可靠的IP的组合

Example

Given “25525511135”,

return [“255.255.11.135”, “255.255.111.35”]. (Order does not matter)

Solution

  • 回溯解。每次判断以当前字符开头的字符串是否属于可靠的子字符串,如果可靠则继续判断后面的,否则跳过。仅当字符串刚好划分为可靠的4个子字符串([0:255])时保存当前组合。在判断每个子字符串时,主要确保 0 <= int(s) <=255,且排除 “01”等情况的子字符串

    public class Solution {
        public List<String> restoreIpAddresses(String s) {
            List<String> res = new ArrayList<>();
            backtracking(s, 0, res, "", 0);
            return res;
        }
    
        /**
         * 思路:每次判断以开始索引的字符开头的字符串是否属于可靠的子字符串,如果可靠则继续判断后面的,否则跳过
         *       仅当字符串刚好划分为可靠的4块([0:255])保存结果
         * @param s:需要分割的字符
         * @param start:开始索引
         * @param res:保存结果
         * @param temp:保存当前组合
         * @param count:当前分割的子字符串个数
         */
        public void backtracking(String s, int start, List<String> res, String temp, int count){
            // 如果子字符串个数大于4个或者已经取完了所有字符串的元素,则返回
            if(count > 4 || start > s.length()) return;
    
            // 如果分为4个子字符串时刚好分割完原字符串,则添加到结果集
            if(count == 4 && start == s.length()) res.add(temp);
    
            // 判断以s[start]开始的字符串是否可靠,如果可靠则继续判断后面的,否则跳过
            // 因为字符串的大小不能大于255,所以位数不可能大于3位数
            for(int i = start; i < start + 3; i++){
                // 保证当前i索引没有超出字符串范围
                if(i < s.length()) {
                    String substr = s.substring(start, i + 1);
                    // 如果一个字符串的第一位为0且位数大于1(如01)或者大于255则跳过
                    if ((substr.startsWith("0") && substr.length() > 1) || Integer.parseInt(substr) > 255) continue;
                    //回溯,每当已经分割出3个子字符串,第4个字符串后面不加 "."
                    backtracking(s, i + 1, res, temp + substr + (count == 3 ? "" : "."), count + 1);
                }
            }
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值