Skip to content

Latest commit

 

History

History
103 lines (70 loc) · 2.05 KB

File metadata and controls

103 lines (70 loc) · 2.05 KB

English Version

题目描述

给你一个有效的 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 地址

解法

方法一:直接替换

Python3

class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace('.', '[.]')

Java

class Solution {
    public String defangIPaddr(String address) {
        return address.replace(".", "[.]");
    }
}

TypeScript

function defangIPaddr(address: string): string {
    return address.split('.').join('[.]');
}

C++

class Solution {
public:
    string defangIPaddr(string address) {
        for (int i = address.size(); i >= 0; --i) {
            if (address[i] == '.') {
                address.replace(i, 1, "[.]");
            }
        }
        return address;
    }
};

Go

func defangIPaddr(address string) string {
	return strings.Replace(address, ".", "[.]", -1)
}

...