码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: 93. Restore IP Addresses

时间:2016-08-09 20:47:30      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

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)

给一串数字字符串,返回所有可能的合理ip地址

 

首先分析一个合理的ip地址包含几个条件:

1. 有四个部分,每个部分以 . 隔开

2. 每个部分最大为255,最小为0

3. 每个部分最长3位

 

可以得到几个限制:

1. 给定字符串只包含数字

2. 给定字符串最长为12,最短为4

3. 每个部分最大255,最小为0

4. 每个部分最长3位,0开头则只能为1位

 

算法分析:

总数4个单元,从传入字符串中每次截取开头1到最长3个字符(长度不超过当前字符串长度)作为当前单元,忽略不符合限制的数字,加入到当前得到的ip字符串。以剩下的字符串,当前ip字符串,剩余单元数传入下一次递归。

结束条件:

字符串长度为0,并且剩余单元数为0

 

public class Solution 
{
    public List<String> restoreIpAddresses(String s) 
    {
        List<String> res = new ArrayList<>();
        
        if (s == null || s.length() == 0)
        {
            return res;
        }
        
        helper(s, "", 4, res);
        
        return res;
    }
    
    public void helper(String input, String cur, int partNum, List<String> res)
    {
        if (input == null)
        {
            return;
        }
        
        if (input.length() > partNum * 3 || input.length() < partNum)
        {
            return;
        }
        
        if (input.length() == 0 && partNum == 0)
        {
            res.add(cur);
            return;
        }
        
        for (int i = 1; i <= 3 && i <= input.length(); i++)
        {
            String curTemp = input.substring(0,i);
            String rest = input.substring(i);
            
            if (isValid(curTemp))
            {
                String temp = new String(cur);
                temp += curTemp;
                
                if (partNum > 1)
                {
                    temp += ‘.‘;
                }
                
                helper(rest, temp, partNum-1, res);
            }
        }
    }
    
    public boolean isValid(String s)
    {
        if (s.charAt(0) == ‘0‘)
        {
            return s.equals("0");
        }
        
        int temp = Integer.parseInt(s);
        
        return temp > 0 && temp <= 255;
    }
}

 

LeetCode: 93. Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/snakech/p/5754358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!