LeetCode 题解工作台

IP 地址无效化

给你一个有效的 IPv4 地址 address ,返回这个 IP 地址的无效化版本。 所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 "." 。 示例 1: 输入: address = "1.1.1.1" 输出: "1[.]1[.]1[.]1" 示例 2: 输入: address = "…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们直接将字符串中的 `'.'` 替换为 `'[.]'` 即可。 时间复杂度 ,其中 为字符串的长度。忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个有效的 IPv4 地址 address,返回这个 IP 地址的无效化版本。

所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 "."

 

示例 1:

输入:address = "1.1.1.1"
输出:"1[.]1[.]1[.]1"

示例 2:

输入:address = "255.100.50.0"
输出:"255[.]100[.]50[.]0"

 

提示:

  • 给出的 address 是一个有效的 IPv4 地址
lightbulb

解题思路

方法一:直接替换

我们直接将字符串中的 '.' 替换为 '[.]' 即可。

时间复杂度 O(n)O(n),其中 nn 为字符串的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace('.', '[.]')
speed

复杂度分析

指标
时间complexity is O(n) where n is the length of the input string since each character is processed once. Space complexity is also O(n) because a new string is created for the defanged IP.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks understanding of string manipulation basics and built-in methods.

  • question_mark

    Wants clarity on iteration versus built-in replacements.

  • question_mark

    Looks for awareness of edge cases with input formatting.

warning

常见陷阱

外企场景
  • error

    Forgetting to replace all periods, only handling the first occurrence.

  • error

    Adding extra characters or incorrect brackets, like '[..]' instead of '[.]'.

  • error

    Using regex incorrectly, causing unintended replacements or errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Defang IP addresses with alternative separators like '<.>' instead of '[.]'.

  • arrow_right_alt

    Handling mixed IPv4 and IPv6 addresses, applying defanging only to IPv4 parts.

  • arrow_right_alt

    Return defanged address while also validating correct IPv4 formatting before transformation.

help

常见问题

外企场景

IP 地址无效化题解:String-driven solution … | LeetCode #1108 简单