首页 > 代码库 > LeetCode "Restore IP Addresses"
LeetCode "Restore IP Addresses"
It is all about corner cases.
class Solution {public: vector<string> retv; bool isValid(string &sub) { unsigned cnt = sub.length(); if (cnt == 0 || cnt > 3) return false; if (cnt == 1) return true; else { if (sub[0] == ‘0‘) return false; if (cnt == 2) return true; int n = atoi(sub.c_str()); return n < 256; } } void go(string &in, int iStart, int level, string ret) { if (iStart >= in.size()) return; if (level == 3) { string slst = in.substr(iStart, in.length() - iStart); if (isValid(slst)) { ret += "."; ret += slst; retv.push_back(ret); } return; } // len 1 string ret1 = ret; if(level > 0) ret1 += "."; ret1 += in[iStart]; go(in, iStart + 1, level + 1, ret1); // len 2 string ret2 = ret; if(level > 0) ret2 += "."; string sub2 = in.substr(iStart, 2); if (isValid(sub2)) { ret2 += sub2; go(in, iStart + 2, level + 1, ret2); } // len 3 string sub = in.substr(iStart, 3); if (isValid(sub)) { string ret3 = ret; if (level > 0) ret3 += "."; ret3 += sub; go(in, iStart + 3, level + 1, ret3); } } vector<string> restoreIpAddresses(string s) { if (s.empty()) return retv; go(s, 0, 0, ""); return retv; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。