Skip to main content

< Back to Data Structures and Algorithms

LeetCode 1108 ยท Strings

Defanging an IP Address

Swaps every "." in an address for "[.]", two ways: split and join, or a character at a time from scratch.

Step through it

Examples
Edge cases
address
  1. 20
  2. 51
  3. 52
  4. .3
  5. 14
  6. 05
  7. 06
  8. .7
  9. 58
  10. 09
  11. .10
  12. 011

Output

returns "255[.]100[.]50[.]0"

โœ“ the expected answer

The code

// Original Solution 

/**
 * Defangs an IP address by converting "." to "[.]".
 * For example: "127.0.0.1" becomes "127[.]0[.]0[.]1".
 *
 * @param {string} address
 * @return {string}
 */
 const defangIPaddr = address => {
    // .split() the string into an array of integers
    // .join() the array back into a string, separating items with "[.]".
    return address.split('.').join('[.]')
}

// "From Scratch" Solution

/**
 * Defangs an IP address by converting "." to "[.]".
 * For example: "127.0.0.1" becomes "127[.]0[.]0[.]1".
 *
 * @param {string} address
 * @return {string}
 */
 const defangIPaddrFromScratch = address => {
	// Stores the new defanged address.
    let defangedAddr = ''
    
	// O(n) loop over every character within the address.
    for (let i=0; i < address.length; i++) {
		// The character.
        const char = address.charAt(i)
        
		// Character is a period.
        if (char === '.') {
			// Defang the period. Append the defanged character to the new string.
            defangedAddr += '[.]'
        } else {
			// Append the character to the new string.
            defangedAddr += char
        }
        
    }
    
	// Address is now defanged.
    return defangedAddr
}

The original on GitHub (opens in a new tab)