首页 > 代码库 > 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)
vector<string> restoreIpAddresses(string s) { vector<string> res; int n = s.length(); if(s=="" || n > 12) return res; for(int i = 0 ; i < 3; ++ i){ for(int j = i+1; j < min(i+4,n-2); ++ j){ for(int k = j+1; k < n-1; ++ k){ string a = s.substr(0,i+1); int aa = stoi(a); string b = s.substr(i+1,j-i); int bb = stoi(b); string c = s.substr(j+1,k-j); int cc = stoi(c); string d = s.substr(k+1); int dd = stoi(d); if(aa >=0 && aa <= 255 && bb>=0 && bb <=255 && cc >= 0 && cc <=255 && dd >= 0 && dd<=255){ string str_a = to_string(aa), str_b = to_string(bb), str_c = to_string(cc), str_d = to_string(dd); if(str_a.length() == a.length() && str_b.length() == b.length() && str_c.length() == c.length() && str_d.length() == d.length() ){ string str = str_a+"."+str_b+"."+str_c+"."+str_d; res.push_back(str); } } } } } return res;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。