Given a valid (IPv4) IP
A defanged IP address replaces every period
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"
Approach
Java
public class DefangingIPAddress {public static void main(String[] args) {String address = "1.1.1.1";System.out.println(defangIPaddr(address));}static String defangIPaddr(String address) {String str = "";String ans = "";int n = address.length();for (int i = 0; i < n; i++) {if (address.charAt(i) != '.')str += address.charAt(i);else {ans += str;ans += "[.]";str = "";}}ans += str;return ans;}}
C++
#include <bits/stdc++.h>using namespace std;string defangIPaddr(string address){string str = "";string ans = "";int n = address.size();for (int i = 0; i < n; i++){if (address[i] != '.')str += address[i];else{ans += str;ans += "[.]";str = "";}}ans += str;return ans;}int main(){string address = "1.1.1.1";cout << defangIPaddr(address);return 0;}
No comments:
Post a Comment