-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1108-defanging_ip_address.py
64 lines (52 loc) · 1.73 KB
/
1108-defanging_ip_address.py
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
"""
https://leetcode.com/problems/defanging-an-ip-address/submissions/
Strat:
Iterate through address & build the return string as you go.
"""
class Solution(object):
"""
Runtime: 8 ms, faster than 99.53% of Python online submissions for Defanging an IP Address.
Memory Usage: 12.8 MB, less than 22.53% of Python online submissions for Defanging an IP Address.
"""
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
result = ""
for char in address:
if char == ".":
result += "[.]"
else:
result += char
return result
"""
According to comments, doing += on a string builds a new string, which makes sense, because
strings are immutable. So here, we connect all the chars and then join them at the end.
Runtime: 12 ms, faster than 95.63% of Python online submissions for Defanging an IP Address.
Memory Usage: 12.6 MB, less than 86.26% of Python online submissions for Defanging an IP Address.
"""
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
#Constants
FANGED_IP = "."
DEFANGED_IP = "[.]"
result = []
for char in address:
if char == FANGED_IP:
result.append(DEFANGED_IP)
else:
result.append(char)
return "".join(result)
"""
Of course you can also do this--"One liners", right?
"""
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
return address.replace(".", "[.]")