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:
Given25525511135,

Return[255.255.11.135, 255.255.111.35]. (Order does not matter)

Solution:

Main Idea: add one by one to the final ip address in recursive Mode

 

void formIpAddr(vector
 
  &ret, string curIp, string nums, int idxIp){        if(idxIp==1){            if(nums.size()>3 || (nums.size()>1&&nums[0]=='0')){                return ;            }            const char * data=nums.c_str();            if(nums.size()<=2||atoi(data)<=255){                ret.push_back(curIp+nums);                return;            }        }        else{            if(nums[0]=='0'){                string tmp=curIp+nums.substr(0,1)+.;                formIpAddr(ret, tmp, nums.substr(1), idxIp-1);                return;            }            else{                int i;                string tmp;                for(i=0; i<2 && i+idxIp<=nums.size(); i++){                    tmp=nums.substr(0, i+1);                    formIpAddr(ret, curIp+tmp+., nums.substr(i+1), idxIp-1);                }                if(i+idxIp<=nums.size()){                    const char * data=nums.substr(0,i+1).c_str();                    tmp=nums.substr(0, i+1);                    if(atoi(data)<=255)                        formIpAddr(ret, curIp+tmp+., nums.substr(i+1), idxIp-1);                }            }        }            }    vector
  
    restoreIpAddresses(string s) {        vector
   
     ret;        if(s.size()<4)            return ret;        string curIp=;                formIpAddr(ret, curIp, s, 4);        return ret;    }
   
  
 


 

 

 

 

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.