diff --git a/solutions/1101-1200/1108-defanging-an-ip-address/README.md b/solutions/1101-1200/1108-defanging-an-ip-address/README.md new file mode 100644 index 0000000..cd8740b --- /dev/null +++ b/solutions/1101-1200/1108-defanging-an-ip-address/README.md @@ -0,0 +1,11 @@ +# 1108. Defanging an IP Address + +[LeetCode problem 1108](https://leetcode.com/problems/defanging-an-ip-address/) + +- **Difficulty**: Easy +- **Tags**: string + +## Description + +Given a valid IPv4 address, return a defanged version of it, replacing every +`.` with `[.]`. diff --git a/solutions/1101-1200/1108-defanging-an-ip-address/solution.cpp b/solutions/1101-1200/1108-defanging-an-ip-address/solution.cpp new file mode 100644 index 0000000..f2660f5 --- /dev/null +++ b/solutions/1101-1200/1108-defanging-an-ip-address/solution.cpp @@ -0,0 +1,20 @@ +#include "solution.hpp" + +namespace leetcode::p1108 { + +std::string solve(const std::string& address) { + std::string result; + result.reserve(address.size()); + + for (char c : address) { + if (c == '.') { + result += "[.]"; + } else { + result += c; + } + } + + return result; +} + +} // namespace leetcode::p1108 diff --git a/solutions/1101-1200/1108-defanging-an-ip-address/solution.hpp b/solutions/1101-1200/1108-defanging-an-ip-address/solution.hpp new file mode 100644 index 0000000..dba1517 --- /dev/null +++ b/solutions/1101-1200/1108-defanging-an-ip-address/solution.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace leetcode::p1108 { + +// optimized: O(n) time, O(n) space — build the result one character at a +// time, expanding '.' into "[.]". +std::string solve(const std::string& address); + +} // namespace leetcode::p1108 diff --git a/solutions/1101-1200/1108-defanging-an-ip-address/test.cpp b/solutions/1101-1200/1108-defanging-an-ip-address/test.cpp new file mode 100644 index 0000000..1ac1d6d --- /dev/null +++ b/solutions/1101-1200/1108-defanging-an-ip-address/test.cpp @@ -0,0 +1,8 @@ +#include + +#include "solution.hpp" + +TEST_CASE("Problem 1108", "[p1108]") { + CHECK(leetcode::p1108::solve("1.1.1.1") == "1[.]1[.]1[.]1"); + CHECK(leetcode::p1108::solve("255.100.50.0") == "255[.]100[.]50[.]0"); +} diff --git a/swift/1108.swift b/swift/1108.swift deleted file mode 100644 index 12b2869..0000000 --- a/swift/1108.swift +++ /dev/null @@ -1,17 +0,0 @@ -func defangIPaddr(_ address: String) -> String { - var result = "" - - for char in address { - if char != "." { - result.append(char) - } else { - result.append("[.]") - } - } - - return result -} - -var test1 = "1.1.1.1" -let result = defangIPaddr(test1) -print(result) // 1[.]1[.]1[.]1 \ No newline at end of file