Skip to content

Commit

Permalink
Restore IP Addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 16, 2023
1 parent ca4a30c commit a5eb7de
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,7 @@ add_task(repeated-dna-sequences)
add_task(repeated-string-match)
add_task(repeated-substring-pattern)
add_task(reshape-the-matrix)
add_task(restore-ip-addresses)
add_task(restore-the-array)
add_task(reverse-bits)
add_task(reverse-integer)
Expand Down
1 change: 1 addition & 0 deletions solutions/restore-ip-addresses/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_restore_ip_addresses test.cpp)
52 changes: 52 additions & 0 deletions solutions/restore-ip-addresses/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#pragma once

#include <string>
#include <vector>

class Solution {
public:
static std::vector<std::string> restoreIpAddresses(std::string s) {
std::vector<std::string> addresses;
std::vector<std::string> parts;
restoreIpAddresses(0, s, &parts, &addresses);
return addresses;
}

private:
static void restoreIpAddresses(size_t i, const std::string &s,
std::vector<std::string> *parts,
std::vector<std::string> *addresses) {
if (i == s.size() && parts->size() == 4) {
addresses->push_back(buildIpAddress(*parts));
return;
}
if (i == s.size() || parts->size() == 4) {
return;
}
for (auto n : {1, 2, 3}) {
if (i + n > s.size()) {
return;
}
if (n > 1 && s[i] == '0') {
return;
}
if (255 < std::stoi(s.substr(i, n))) {
return;
}
parts->push_back(s.substr(i, n));
restoreIpAddresses(i + n, s, parts, addresses);
parts->pop_back();
}
}

static std::string buildIpAddress(const std::vector<std::string> &parts) {
std::string address;
for (size_t i = 0; i < 4; ++i) {
address += parts[i];
if (i != 3) {
address += '.';
}
}
return address;
}
};
31 changes: 31 additions & 0 deletions solutions/restore-ip-addresses/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::string s;
std::vector<std::string> expected;
};

std::vector<TestCase> test_cases{
{
.s = "25525511135",
.expected{"255.255.11.135", "255.255.111.35"},
},
{
.s = "0000",
.expected{"0.0.0.0"},
},
{
.s = "101023",
.expected{"1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3",
"101.0.2.3"},
},
};

for (const auto &[s, expected] : test_cases) {
const auto actual = Solution::restoreIpAddresses(s);
REQUIRE(expected == actual);
}
}

0 comments on commit a5eb7de

Please sign in to comment.