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)
class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> ret; string ip; ipAddresses(s,0,ip,ret); return ret; } private: void ipAddresses(string &s,int index,string &ip,vector<string> &ret){ const int n=s.size(); if(index==n){ trim_dot(ip); if(count(ip.begin(),ip.end(),'.')!=3) return; ret.push_back(ip); return; } for(int i=index;i<n;i++){ if((i-index)>2)return; if(s[index]=='0' && i>index) return; string temp=ip; if(isIPFormat(s,index,i,ip)){ ip=ip+'.'+s.substr(index,i-index+1); ipAddresses(s,i+1,ip,ret); } ip=temp; //撤回 } } bool isIPFormat(string &s,int index,int i,string &ip){ string cur=s.substr(index,i-index+1); int n=atoi(cur.c_str()); if(n<0 || n>255) return false; trim_dot(ip); int m=std::count(ip.begin(),ip.end(),'.'); if (m>2)return false; return true; } void trim_dot(string &s){ s.erase(0,s.find_first_not_of(".")); s.erase(s.find_last_not_of(".")+1); } };