LeetCode 题解工作台
IP 地址无效化
给你一个有效的 IPv4 地址 address ,返回这个 IP 地址的无效化版本。 所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 "." 。 示例 1: 输入: address = "1.1.1.1" 输出: "1[.]1[.]1[.]1" 示例 2: 输入: address = "…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们直接将字符串中的 `'.'` 替换为 `'[.]'` 即可。 时间复杂度 ,其中 为字符串的长度。忽略答案的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个有效的 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 地址
解题思路
方法一:直接替换
我们直接将字符串中的 '.' 替换为 '[.]' 即可。
时间复杂度 ,其中 为字符串的长度。忽略答案的空间消耗,空间复杂度 。
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]')
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.