Restore IP Addresses

Source: Internet
Author: User

Restore IP Addresses

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)

public class Solution {    public List
 
   restoreIpAddresses(String s) {        List
  
    res=new LinkedList
   
    ();        if(s==null || s.length()<=3) return res;        dfs(0,0,new String(""),s,res);        return res;    }    public void dfs(int start,int points,String IPstr,String s,List
    
      res){        if(start==s.length()&& points==4){            IPstr=IPstr.substring(0,IPstr.length()-1);            res.add(IPstr);            return;        }        if(points>=4) return;        if(s.length()-start<4-points) return;        if(s.length()-start>(4-points)*3) return;        if(start+1<=s.length()){            String sub1=s.substring(start,start+1);            dfs(start+1,points+1,IPstr+sub1+".",s,res);        }        if(start+2<=s.length()){            String sub2=s.substring(start,start+2);            if(sub2.compareTo("10")>=0 && sub2.compareTo("99")<=0){                dfs(start+2,points+1,IPstr+sub2+".",s,res);            }        }        if(start+3<=s.length()){            String sub3=s.substring(start,start+3);            if(sub3.compareTo("100")>=0 && sub3.compareTo("255")<=0){                dfs(start+3,points+1,IPstr+sub3+".",s,res);            }        }    }}
    
   
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.