Leetcode 1108. Defanging an IP Address
You are given a valid IPv4 address address
. Return a defanged version of that IP address.
A defanged IP address replaces every period .
with [.]
.
Before we jump into solving the problem, let’s ensure we understand all the requirements and constraints:
[.]
).
).[.]
to the output string instead of the period.Here’s the implementation in C++:
#include <iostream>
#include <string>
class Solution {
public:
std::string defangIPaddr(std::string address) {
std::string defangedAddress;
for (char c : address) {
if (c == '.') {
defangedAddress += "[.]";
} else {
defangedAddress += c;
}
}
return defangedAddress;
}
};
int main() {
Solution solution;
std::string address = "1.1.1.1";
std::string result = solution.defangIPaddr(address);
std::cout << "Defanged IP Address: " << result << std::endl;
return 0;
}
address
. We are iterating through each character of the string once.address
. We need to store the new string, which in the worst case can be up to twice the length of the original string (if all characters are periods).This approach should work efficiently for the given problem constraints and typical input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?