For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
.
思路:递归尝试。ip地址十进制形式的一个段的范围是0~255,而且注意避免0*和0**的情况。当字符串到头或者到达4个段的时候,停止尝试。
代码:
class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> result; if(s.size() == 0) return result; string cur = ""; find(s, 0, 0, cur, result); return result; } void find(string s, int from, int count, string cur, vector<string> &result) { if(from == s.size() && count == 4) { cur.erase(cur.end()-1); result.push_back(cur); return; } if(count == 4) return; if(from == s.size()) return; if(from+2 < s.size() && s[from] != '0' && s.substr(from, 3) <= "255") { cur += s.substr(from, 3) + "."; find(s, from+3, count+1, cur, result); cur.erase(cur.end()-4, cur.end()); } if(from+1 < s.size() && s[from] != '0') { cur += s.substr(from, 2) + "."; find(s, from+2, count+1, cur, result); cur.erase(cur.end()-3, cur.end()); } cur += s.substr(from, 1) + "."; find(s, from+1, count+1, cur, result); } };