标签:
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)
Tags: Backtracking String
输入一个字符串,要求输出该字符串可能拆分成的ip地址形式。
思路:ipv4的地址应该是4段,每段0-255中的一个数。所以考虑4层DFS加一些剪枝条件即可。剪枝条件有:1、取3个字符串stoi作为地址时大于255;2、2位数或者3位数地址段以0开头
另外要检查第四段ip地址为0的情况,防止类似于"0000000"atoi之后也算作0的情况。
1 class Solution { 2 public: 3 4 bool dfs(string input, int number, string ipAddress, vector<string> &result){ 5 if(input.length() == 0){ 6 return false; 7 } 8 if(number == 3){ 9 int addressNumber = stoi(input); 10 if(input[0] == ‘0‘){ 11 if(!(input.length() == 1 && addressNumber == 0)) 12 return false; 13 } 14 if(addressNumber <= 255){ 15 ipAddress = ipAddress + input; 16 result.push_back(ipAddress); 17 return true; 18 }else{ 19 return false; 20 } 21 }else{ 22 if(input.length() >= 1){ 23 dfs(input.substr(1), number + 1, ipAddress + input.substr(0, 1) + ".", result); 24 } 25 if(input.length() >= 2 && input[0] != ‘0‘){ 26 dfs(input.substr(2), number + 1, ipAddress + input.substr(0, 2) + ".", result); 27 } 28 if(input.length() >= 3 && input[0] != ‘0‘){ 29 int addressNumber = stoi(input.substr(0, 3)); 30 if(addressNumber <= 255){ 31 dfs(input.substr(3), number + 1, ipAddress + input.substr(0, 3) + ".", result); 32 } 33 } 34 } 35 return true; 36 } 37 38 vector<string> restoreIpAddresses(string s) { 39 vector<string> result; 40 if(s.length() == 0 || s.length() > 12){ 41 return result; 42 } 43 string temp = ""; 44 dfs(s, 0, temp, result); 45 return result; 46 } 47 };
标签:
原文地址:http://www.cnblogs.com/suwish/p/5204835.html