From 0dfe4ed7338f255076da009e8ae974ca3d76ea2e Mon Sep 17 00:00:00 2001 From: Powfu <1875065753@qq.com> Date: Tue, 26 Dec 2023 13:06:17 +0000 Subject: [PATCH] =?UTF-8?q?add=202101040022/chapter=5F5/=E6=81=A2=E5=A4=8D?= =?UTF-8?q?IP=E5=9C=B0=E5=9D=80.cpp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Powfu <1875065753@qq.com> --- ...345\244\215IP\345\234\260\345\235\200.cpp" | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 "2101040022/chapter_5/\346\201\242\345\244\215IP\345\234\260\345\235\200.cpp" diff --git "a/2101040022/chapter_5/\346\201\242\345\244\215IP\345\234\260\345\235\200.cpp" "b/2101040022/chapter_5/\346\201\242\345\244\215IP\345\234\260\345\235\200.cpp" new file mode 100644 index 00000000..14e42577 --- /dev/null +++ "b/2101040022/chapter_5/\346\201\242\345\244\215IP\345\234\260\345\235\200.cpp" @@ -0,0 +1,54 @@ +#include +using namespace std; +class Solution { +public: + vector res; + vector restoreIpAddresses(string s) { + if (s.size() > 12) + return res; + //cur为当前分割的一种情况,pos当前s下标,cnt计数 + string cur; + Recursion(s, cur, 0, 0); + return res; + } + void Recursion(string &s, string cur, int pos, int cnt) + { + if (pos == s.size()) + { + //当pos到尾且cnt=4,则是正确分割,否则返回 + if (cnt == 4) + { + cur.pop_back(); + res.push_back(cur); + } + return; + } + //Ip地址每一部分可能是一位数0-9 + cur += s.substr(pos, 1) + '.'; + Recursion(s, cur, pos + 1, cnt + 1); + cur.erase(cur.size() - 2, 2); + //Ip地址每一部分可能是两位数10-99 + if (pos + 1 < s.size() && s[pos] != '0') + { + cur += s.substr(pos, 2) + '.'; + Recursion(s, cur, pos + 2, cnt + 1); + cur.erase(cur.size() - 3, 3); + } + //Ip地址每一部分可能是三位数100-255 + if (pos + 2 < s.size() && (s[pos] == '1'|| (s[pos]=='2' && s.substr(pos,3)<="255"))) + { + cur += s.substr(pos, 3) + '.'; + Recursion(s, cur, pos + 3, cnt + 1); + cur.erase(cur.size() - 4, 4); + } + return; + } +}; +int main() +{ + Solution solute; + string s = "172162541"; + vector res = solute.restoreIpAddresses(s); + copy(res.begin(), res.end(), ostream_iterator(cout, "\n")); + return 0; +} \ No newline at end of file -- Gitee