LeetCode 87.复原IP地址

题目地址:Leecode地址

1.问题思路

切割问题采用回溯思想,一般使用DFS查找。
首先观察一下ipv4地址的特点:
① 总共有4段。
② 每段区间为0~255。
按题意,是想将一段字符串分为4段子串,且每段子串的区间为0~255。
这题是典型的回溯思路,可按DFS进行查找,且当前层从【startIndex, s.length】,下层的遍历区间【startIndex+1, s.length】,且深度最大为4。

2.代码实现

 class Solution {
        List<String> result = new ArrayList<String>();
        StringBuilder path = new StringBuilder();
        int count = 4;
        public List<String> restoreIpAddresses(String s) {
            dfs(s, 0);
            return result;
        }

        /**
         * 切割字符串
         * 1.只能切割成4个子串
         * 2.每个子串不能超过255
         *
         * @param s
         * @param startIndex
         */
        public void dfs(String s, int startIndex) {
            // 已经达到了4层且字符串已经遍历完
            if (startIndex >= s.length() && count<=0) {
                String item = path.toString();
                result.add(item.substring(0, item.length()-1));
                return;
            }

            if (count <= 0) {
                return;
            }
			
			// 每层的遍历区间
            for (int i = startIndex; i < s.length(); i++) {
                String item = s.substring(startIndex, i+1);
                // ip每位不能超过255, 且首位必须大于0
                if (item.length() > 3 || Integer.parseInt(item) > 255 || (item.length() > 1 && item.startsWith("0"))) {
                    continue;
                }

                count--;
                path.append(item).append(".");
                dfs(s, i+1);
                count++; // 回溯
                path.delete(path.length() - item.length()-1, path.length());
            }
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值