forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1108. Defanging an IP Address.cpp
64 lines (50 loc) · 1.28 KB
/
1108. Defanging an IP Address.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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.
class Solution {
public:
string defangIPaddr(string address) {
string res;
string tmp="[.]";
int n=address.length();
for(int i=0;i<n;i++){
if(address[i]=='.'){
res+=tmp;
} else res+=address[i];
}
return res;
}
};
class Solution {
public:
string defangIPaddr(string address) {
int n=address.length();
int cnt=0;
for(int i=0;i<n;i++){
if(address[i]=='.') cnt++;
}
int last=n+(cnt*2);
while(cnt--){
address+=" ";
}
for(int i=n-1,j=last-1; i>=0;i--){
if(address[i]=='.'){
address[j]=']';
address[j-1]='.';
address[j-2]='[';
j-=3;
} else {
address[j]=address[i];
j-=1;
}
}
return address;
}
};