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)
三重循环,遍历三个小数点的位置,对每个位置check一下即可。
注意:
stoi函数默认要求输入的参数字符串是符合int范围的[-2147483648, 2147483647],否则会runtime error。
atoi函数则不做范围检查,若超过int范围,则显示-2147483648(溢出下界)或者2147483647(溢出上界)。
class Solution public: vector<string> restoreIpAddresses(string s) vector<string> ret; if(s.size() > 12) return ret; for(int i = 0; i < s.size(); i ++) // [0, i] for(int j = i+1; j < s.size(); j ++) // [i+1, j] for(int k = j+1; k < s.size()-1; k ++) // [j+1, k], [k+1, s.size()-1] string ip1 = s.substr(0, i+1); string ip2 = s.substr(i+1, j-i); string ip3 = s.substr(j+1, k-j); string ip4 = s.substr(k+1); if(check(ip1) && check(ip2) && check(ip3) && check(ip4)) string ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4; ret.push_back(ip); return ret; bool check(string ip) int value = stoi(ip); if(ip[0] == ‘0‘) return (ip.size() == 1); else if(value <= 255) return true; else return false; ;