leetcode -- 93. Restore IP Addresses

题目描述

题目难度:Medium

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”]

AC代码

leetcode 一位大神的代码,和我思路一致,但是他的实现更细致,更优雅
https://leetcode.com/problems/restore-ip-addresses/discuss/251206/0ms-java-solution

note:1.01.02.1 不是合法的ip地址,也就是说数字不可以以0开头,除了0之外。

class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> ans = new ArrayList();
        if (s.length() > 3 && s.length() < 13) //预判断
            help(s, new char[s.length()+3], 0, ans, 0, 0);
        return ans;
    }
    
    /**
    s:原s
    cs:存放ip的数组
    count:ip由 A.B.C.D 四部分组成,count 表示cs中现有ip部分的个数
    ans:返回值
    start:s中正在遍历的开始位置
    i:cs中下一个存放字符位置的下标
    */
    void help(String s, char[] cs, int count, List<String> ans, int start, int i){
        int digit = 0;
        for (int l = start; l < 3+start && l < s.length(); l++){ //ip的一个部分最多由三个数字构成,同时还要保证l没有超出s的范围
            digit = 10*digit + (s.charAt(l)-'0');
            if (digit > 255) return;
            cs[i++] = s.charAt(l);
            if (count == 3){ //之前已经存在ip的三部分
                if (l+1==s.length()) ans.add(new String(cs)); //l已经到了s的末尾
            }else{
                cs[i] = '.';
                help(s, cs, count+1, ans, l+1, i+1);
            }
            if (digit == 0) return; //这一步挺关键的,为了防止ip一部分的值类似于 01,010的存在
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值