LeetCode Tag: Back tracking

LeetCode 93 Restore IP Addresses

Description

Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

Solution

  1. 问题是要把一段字符串转换成可能的ip地址
  2. 定义返回变量solutions
  3. 传入restoreIp函数中
  • restoreIp 函数有四个参数原始的ip字符串、 返回结果solutions、idx(当前ip的索引)、restored、count(用来记录切割的ip段, ip总共四段)
  • count > 4 就返回
  • count == 4 && idx == ip的长度,意味着完成了ip地址的转换,并将存储的变量restored 加入到 solutions中
  • 进行for循环 i = 1 2 3

如果idx+i > ip.length() 跳出循环
s = ip.substring(idx, idx+i)
s以0开始而且长度大于1 || i = 3&&s>256 跳过下一条语句
递归调用restoreIp(ip, solutions, idx移动i, restored + s + (count == 3 ? "" : "."), count +1);

Code

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> solutions = new ArrayList<>();
        restoreIp(s, solutions, 0, "", 0);
        return solutions;
    }
    
    private void restoreIp(String ip, List<String> solutions, int idx, String restored, int count) {
        if(count > 4) return;
        if(count == 4 && idx == ip.length()) {
            solutions.add(restored);
        }
        for(int i = 1; i < 4; i++) {
            if(idx + i > ip.length()) break;
            String s = ip.substring(idx, idx+i);
            if ((s.startsWith("0") && s.length() > 1) || (i == 3 && Integer.parseInt(s) >= 256)) 
                continue;
            
            restoreIp(ip, solutions, idx+i, restored+s+(count == 3 ? "" : "."), count+1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 50个常用的sql语句Student(S#,Sname,Sage,Ssex) 学生表Course(C#,Cname...
    哈哈海阅读 1,256评论 0 7
  • 从来被教坚持,怎样都要坚持,却从没有被教放弃。 所以,哪怕只有一线生机一丝可能,我们大概都会选择坚持而不是放弃。 ...
    清韵难敲阅读 513评论 0 0
  • 旅行与读书,先有读书,还是先有旅行?就如同先有鸡还是先有蛋一般,在还未得到科学证明前,人们总是各有说辞,奇怪的是这...
    正记录Beta阅读 707评论 1 14