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

lintcode-medium-Restore IP Addresses

时间:2016-04-05 07:07:57      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Example

Given "25525511135", return

[
  "255.255.11.135",
  "255.255.111.35"
]

Order does not matter.

 

public class Solution {
    /**
     * @param s the IP string
     * @return All possible valid IP addresses
     */
    public ArrayList<String> restoreIpAddresses(String s) {
        // Write your code here
        
        ArrayList<String> result = new ArrayList<String>();
        String line = "";
        
        helper(result, line, 0, s, 0);
        
        return result;
    }
    
    public void helper(ArrayList<String> result, String line, int start, String s, int count){
        
        if(count == 4){
            if(start == s.length()){
                line = line.substring(0, line.length() - 1);
                result.add(line);
                return;
            }
            else
                return;
        }
        
        for(int i = start + 1; i <= start + 3 && i <= s.length(); i++){
            if(valid(s.substring(start, i))){
                String new_line = line + s.substring(start, i) + ".";
                helper(result, new_line, i, s, count + 1);
            }
        }
        return;
    }
    
    public boolean valid(String s){
        if(s.charAt(0) == ‘0‘ && s.length() > 1)
            return false;
        
        int temp = Integer.parseInt(s);
        
        return (temp >= 0 && temp <= 255);
    }
    
}

 

lintcode-medium-Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5353633.html

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