原题链接在这里:https://leetcode.com/problems/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 "[.]"
.
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"
Constraints:
- The given
address
is a valid IPv4 address.
题解:
Replace all "." with "[.]".
Time Complexity: O(n). n = address.length().
Space: O(n).
AC Java:
1 class Solution { 2 public String defangIPaddr(String address) { 3 if(address == null || address.length() == 0){ 4 return address; 5 } 6 7 StringBuilder sb = new StringBuilder(); 8 for(int i = 0; i<address.length(); i++){ 9 char c = address.charAt(i); 10 if(c == '.'){ 11 sb.append("[.]"); 12 }else{ 13 sb.append(c); 14 } 15 } 16 17 return sb.toString(); 18 } 19 }