--- IP address back division

IP address is divided

93. Restore IP Addresses(Medium)

Given "25525511135",
return ["255.255.11.135", "255.255.111.35"].

Subject description:

  According to the given string and returns all the legal division of the IP address.

Analysis of ideas:

  This question is actually a depth-first traversal of the process. ip has four segments, each segment the number of characters may be 1, 2, each segment of the cycle therefore take 1,2,3, then mark the current ip corresponding to the segment which segment until the segment has been divided ip four segments, and take the time to take over this string to a legitimate ip into the final result. Processing for each time if taken according to the i-th character after each treatment, the following block fetch recursive call needs to be taken in front of the i-th character is removed, because if it satisfies the condition where the back must have been taken through the result of . Now we need a new beginning from the process.

Code:

public List<String>restoreIpAddresses(String s){
    List<String>res=new ArrayList<>();
    if(s==null||s.length()==0)
        return res;
    StringBuilder str=new StringBuilder();
    findIp(0,s,str,res);
    return res;
}
public void findIp(int k,String s,StringBuilder str,List<String>res){
    if(k==4||s.length()==0){
        if(k==4&&s.length()==0)//分成了四段并且str没有剩余
            res.add(str.toString());
        return ;
    }
    for(int i=0;i<s.length()&&i<=2;i++){
        if(i!=0&&s.charAt(0)=='0')
            break;    //该段的长度不为1,但是字符串首字母为0,那么不符合ip命名方式,直接退出,例如:01.100.22.33其地址应该为1.100.22.33
        String part=s.substring(0,i+1); 
        if(Integer.valueOf(part)<=255){
            if(str.length()!=0){//不是首段,则要加上段分隔符
                part='.'+part;
            }
            str.append(part); //添加
            findIp(k+1,s.substring(i+1),str,res); //k表示第几段
            str.delete(str.length()-part.length(),str.length()); //删除
        }
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11111023.html