标签:大于 restore log span store tin lintcode string lint
1 class Solution { 2 public: 3 /* 4 * @param s: the IP string 5 * @return: All possible valid IP addresses 6 */ 7 vector<string> restoreIpAddresses(string &s) { 8 // write your code here 9 vector<string> ans; 10 dfs(s, 0, ans, "", 0); 11 return ans; 12 } 13 void dfs(string &s, int pos, vector<string> &ans, string res, int cnt){ 14 if(pos >= s.length() && cnt == 4){ 15 ans.push_back(res); 16 return ; 17 } else { 18 for(int i = 0; i <= 2; ++i){ 19 if(pos + i < s.length()){ 20 string tmp = s.substr(pos, i + 1);21 int num = atoi(tmp.c_str()); 22 if((num == 0 && tmp.length() != 1) || (num != 0 && tmp[0] == ‘0‘)) continue; 23 string nres = ""; 24 if(i == 2){ 25 if(num < 256){ 26 if(pos != 0) 27 nres = res + "." + tmp; 28 else nres = res + tmp; 29 dfs(s, pos + i + 1, ans, nres, cnt + 1); 30 } 31 } else { 32 if(pos != 0) 33 nres = res + "." + tmp; 34 else nres = res + tmp; 35 dfs(s, pos + i + 1, ans, nres, cnt + 1); 36 } 37 } 38 } 39 } 40 } 41 };
ip地址的每个区域值不大于255 且不能有前导零
标签:大于 restore log span store tin lintcode string lint
原文地址:http://www.cnblogs.com/GeniusYang/p/7544912.html