首页 > 代码库 > [LeetCode] Restore IP Addresses
[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};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。