【LeetCode】解析_1108. Defanging an IP Address

Given a valid (IPv4) IP address, return a defanged version of that IP address.

defanged IP address replaces every period "." with "[.]".

Example 1:

Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1"

Example 2:

Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"

題目網址

這題不會很難,只是把IP4的 ".",改成 "[.]"

方法1. 暴力破解

public class Solution {
    public string DefangIPaddr(string address) {
        var newString = string.Empty;
            string replaceText = "[.]";

            for(int i = 0; i < address.Length; i++)
            {
                if (address[i] == '.')
                {
                    newString += replaceText;
                }
                else
                {
                    newString += address[i];
                }
            }
        return newString;
    }
}

方法2. 友善方法

C# 個方法叫做 String.Replace 方法

public String Replace(char oldChar,char newChar)

public defangIPaddr(string address){
   return address.replace(".", "[.]")
}
   

 

主要是做我的學習筆記

偶而心血來潮寫個幾篇~

若有問題~可以寫信或在下方留言~感謝