LeetCode-1108.IP 地址无效化

94 阅读1分钟

题目:

给你一个有效的 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 地址
  1. java版本:
class Solution { 
    public String defangIPaddr(String address) { 
        char[] ch = new char[address.length()+3*2]; 
        int j = 0; 
        for(int i=0; i<address.length(); ++i) { 
            char c = address.charAt(i); 
            if(c != '.') { 
                ch[j++] = c; 
            } else { 
                ch[j++] = '['; 
                ch[j++] = '.'; 
                ch[j++] = ']'; 
            } 
         } 
         return new String(ch); 
     } 
     
    public static void main(String[] args) {
        Solution test = new Solution();
        System.out.println(test.defangIPaddr("255.100.50.0"));
    }
}
  1. c版本
#include<stdio.h>  
#include<stdlib.h>  
#include <string.h>
  
char* defangIPaddr(char* address) {  
    char* str = malloc(sizeof(char)*(strlen(address)+7));  
    char* temp = str;  
    while (*address)  
    {  
        if (*address != '.') 
            *temp++ = *address++; 
        else  
        {  
            *temp++ = '[';  
            *temp++ = '.';  
            *temp++ = ']';  
            address++;  
        }  
    }  
    *temp = '\0';  
    return str;  
}  
  
int main(void)  
{  
    char str[] = "255.100.50.0";  
    char* result = defangIPaddr(str);  
    printf("%s", result);  
    return 0;  
}