[LeetCode] 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)
class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> res; int len = s.size(); if(len<4) return res; for(int i=0;i<len-2;i++) for(int j=i+1;j<len-1;j++) for(int k=j+1;k<len;k++){ if(i-0<=3 && j-i<=3 && k-j<=3){ string sRestore =IsValidAndRestore(i,j,k,s); if(sRestore != "" && find(res.begin(),res.end(),sRestore)==res.end()) res.push_back(sRestore); } }//end for return res; } private: bool valid(string s){//各子串是否合法 istringstream is(s); int res; is>>res; if((s.size()>1 && s[0]=='0')|| res>255 || res<0) return false; else return true; }//end valid string IsValidAndRestore(int x,int y,int z,string s){ string s1 = s.substr(0,x); string s2 = s.substr(x,y-x); string s3 = s.substr(y,z-y); string s4 = s.substr(z); string Res; if(valid(s1) && valid(s2) && valid(s3) && valid(s4)){ return s1+"."+s2+"."+s3+"."+s4; } return Res; }//end IsValid };