标签:style blog io color os sp for on div
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> result; vector<string> ip; if(s.length() < 4 || s.length() > 12) return result; dfs(result, ip, s, 1); return result; } void dfs(vector<string> & result, vector<string> &ip, string s, int level){ if(level == 4){ if(s.length() > 3 || s[0] == ‘0‘&& s.length() != 1) return; if(atoi(s.c_str()) >255) return; ip.push_back(s); string tmp; for(auto i = ip.begin(); i != ip.end(); i++) tmp += *i + "."; tmp.pop_back(); result.push_back(tmp); ip.pop_back(); }else{ if(s[0] == ‘0‘){ ip.push_back("0"); if(s.length() > 1)dfs(result, ip, s.substr(1), level+1); ip.pop_back(); }else{ for(int i = 1; i <=3 && i < s.length(); i++){ string tmp = s.substr(0,i); if(atoi(tmp.c_str()) <= 255){ ip.push_back(tmp); dfs(result, ip, s.substr(i), level+1); ip.pop_back(); } } } } } };
Leetcode: Restore IP Addresses
标签:style blog io color os sp for on div
原文地址:http://www.cnblogs.com/Kai-Xing/p/4138595.html