---
# System prepended metadata

title: 1108. Defanging an IP Address
tags: [LeetCode]

---

---
tags: LeetCode
---

# 1108. Defanging an IP Address

Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".

1. Example 1:
- Input: address = "1.1.1.1"
- Output: "1[.]1[.]1[.]1"
2. Example 2:
- Input: address = "255.100.50.0"
- Output: "255[.]100[.]50[.]0"

Constraints:
- The given address is a valid IPv4 address.

---
輸入範本如下
```
public class Solution {
    public string DefangIPaddr(string address)
    {
         return "";
    }
}
```
自行限制不准使用 
1. address.Replace(".","[.]");
2. string.Join("[.]", address.Split("."))
3. address.Split('.').Aggregate((l, r) => $"{l}[.]{r}");

### 直覺想法
直覺的想法是走訪字串判斷該字元是否為 . 來做相對應的操作
操作目前想到有兩種做法 
1. 使用 Insert 
```C#
// Time complexity: O(n)
// Space complexity: O(n)
public string DefangIPaddr(string address)
{
     var stringBuilder = new StringBuilder(address);
     for (int i = stringBuilder.Length - 2; i > 0; i--)
     {
          if (stringBuilder[i] == '.')
          {
               stringBuilder.Insert(i + 1, "]");
               stringBuilder.Insert(i, "[");
          }
     }
     return stringBuilder.ToString();
}   
``` 
2. 重組一個字串 
```C#
// Time complexity: O(n)
// Space complexity: O(n)
public string DefangIPaddr(string address)
{
     StringBuilder stringBuilder = new StringBuilder();
     foreach(var character in address)
     {
          if (character == '.')
          {
               stringBuilder.Append("[.]");
          }
          else
          {
               stringBuilder.Append(character);
          }
    }
    return stringBuilder.ToString();
}
```










### Thank you! 

You can find me on

- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)

若有謬誤 , 煩請告知 , 新手發帖請多包涵

# :100: :muscle: :tada: :sheep: 
