Defanging an IP Address
💻 coding

Defanging an IP Address

1 min read 122 words
1 min read
ShareWhatsAppPost on X
  • 1A defanged IP address replaces every period '.' with '[.]'.
  • 2The provided solution uses a StringBuilder for efficient string construction.
  • 3Both time and space complexity for the solution are O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A defanged IP address replaces every period '.' with '[.]'."

Defanging an IP Address

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 address is a valid IPv4 address.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 class DefangIPaddrSln
 {
 public void execute()
 {
 var res = DefangIPaddr("255.100.50.0");
 }

 public string DefangIPaddr(string address)
 {
 var str = new StringBuilder();
 for (int i = 0; i < address.Length; i++)
 {
 if (address[i] == '.')
 {
 str.Append("[.]");
 }
 else
 {
 str.Append(address[i]);
 }
 }
 return str.ToString();
 }
 }
}

Time Complexity: O(n) - for one traversal

Space Complexity: O(n) - Construction of StringBuilder

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 4 May 2020 · 1 min read · 122 words

Part of AskGif Blog · coding

You might also like