Defanging an IP Address Problem
Description
LeetCode Problem 1108.
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Constraints:
- The given
addressis a valid IPv4 address.
Solution
Approach: Replace Every Period
Defanging just means writing [.] wherever the address has a .; the numbers stay as they are, and the address does not need to be parsed or checked. Build the result character by character, writing [.] for a period and copying every other character, or use the language's built-in replace.
One thing to watch with built-ins: some of them treat the pattern as a regular expression, where . matches any character. Java's String.replace (unlike replaceAll) and Python's str.replace take plain text, Go's strings.Replace needs -1 to replace every match, and in JavaScript split(".").join("[.]") replaces all periods on old Node versions that have no replaceAll.
Complexity: O(n) time and O(n) space for the new string, where n is the length of the address.
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]")