This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

Thank you very much for reading this article ~ welcome 【👍 like 】【⭐ collect 】【📝 comment 】~ Give up is easy, but insist must be cool ~ HOPE we can all make a little progress every day ~ Original ~ https://juejin.cn/user/2771185768884824/posts blog


1108. Invalid IP address:

Given a valid IPv4 address address, return an invalid version of this IP address.

Invalidating IP addresses means replacing each “.” with “[.]”.

Sample 1

Input: address = "1.1.1.1" Output: "1[.]1[.]1"Copy the code

The sample 2

Input: address = "255.100.50.0" output: "255 [.] 100 [.] 50 [.] 0"Copy the code

prompt

  • Given theaddressIs a valid IPv4 address

Analysis of the

  • This algorithm problem two master believe that we can do, I seem to have no what to say.
  • In fact, the translation of the.Replace them all with[.]
  • In addition toCC++The solution of the problem can focus on the next, the other basic are using the language with its own API.

Answer key

java

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

c

Address is a valid IPv4 address, which means there must be three. [.], you can see that the result is six characters longer than the input parameter. Strlen returns a length that does not contain the hidden character ‘\0’ at the end of the string.

char * defangIPaddr(char * address){
    int n = strlen(address);
    char *ans = malloc(n + 7);
    for (int i = 0, j = 0; i < n; ++i) {
        if (address[i] == '. ') {
            ans[j++] = '[';
            ans[j++] = '. ';
            ans[j++] = '] ';
        } else {
            ans[j++] = address[i];
        }
    }
    ans[n + 6] = '\ 0';
    return ans;
}
Copy the code

c++

I didn’t find the whole API to be replaced at one time. I replaced it in reverse order. Why? If the order is positive, the position of. Will be moved backward after the substitution, so you need to move the subscript, otherwise the loop will be infinite.

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

python

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

go

func defangIPaddr(address string) string {
    return strings.ReplaceAll(address, "."."[the]")}Copy the code

rust

impl Solution {
    pub fn defang_i_paddr(address: String) - >String {
        address.replace("."."[the]")}}Copy the code


The original portal: https://leetcode-cn.com/problems/defanging-an-ip-address/