@@ -24,22 +24,21 @@ def urlify(s: str, true_length: int) -> str:
24
24
# Below link goes over string concat efficiency in python (I will use method 4
25
25
# https://waymoot.org/home/python_string/
26
26
# each space will make us replace it (with '%', then add 2 characters ('2', '0')
27
- result = [ ' \x00 ' ] * len ( s ) * 2 # extra buffer space
28
- i = 0
27
+ # must count spaces first to help us find out the size of the
28
+ result = [ ' \x00 ' ] * true_length * 3
29
29
space_count = 0
30
- added_chars_per_space = 2
31
- for c in s :
32
- if i == true_length + added_chars_per_space * space_count :
33
- break
34
- if c == ' ' :
35
- result [i ] = '%'
36
- result [i + 1 ] = '2'
37
- result [i + 2 ] = '0'
38
- i += 3
30
+ chars_per_space = 2
31
+ idx = 0
32
+ for x in range (true_length ):
33
+ if s [idx - space_count * chars_per_space ] == ' ' :
34
+ result [idx ] = '%'
35
+ result [idx + 1 ] = '2'
36
+ result [idx + 2 ] = '0'
39
37
space_count += 1
38
+ idx += 3
40
39
continue
41
- result [i ] = c
42
- i += 1
40
+ result [idx ] = s [ idx - space_count * chars_per_space ]
41
+ idx += 1
43
42
return '' .join (result ).rstrip ('\x00 ' )
44
43
45
44
@@ -73,7 +72,8 @@ def test_urlify(self):
73
72
(("a b c d e f g h" , 15 ), "a%20b%20c%20d%20e%20f%20g%20h" ),
74
73
(("a b c d e f g h ignore this" , 15 ), "a%20b%20c%20d%20e%20f%20g%20h" ),
75
74
(("ihavenospaces" , 13 ), "ihavenospaces" ),
76
- (("nospacesIgnoreme" , 8 ), "nospaces" )
75
+ (("nospacesIgnoreme" , 8 ), "nospaces" ),
76
+ ((" " , 1 ), "%20" )
77
77
]
78
78
for args , expected in cases :
79
79
self .assertEqual (urlify (* args ), expected , msg = args )
@@ -86,7 +86,8 @@ def test_urlify_no_true_length(self):
86
86
("a b c d e f g h" , "a%20b%20c%20d%20e%20f%20g%20h" ),
87
87
("a b c d e f g h ignore this" , "a%20b%20c%20d%20e%20f%20g%20h%20ignore%20this" ),
88
88
("ihavenospaces" , "ihavenospaces" ),
89
- ("nospacesIgnoreme" , "nospacesIgnoreme" )
89
+ ("nospacesIgnoreme" , "nospacesIgnoreme" ),
90
+ (" " , "%20" )
90
91
]
91
92
for s , expected in cases :
92
93
self .assertEqual (urlify_no_true_length (s ), expected , msg = s )
0 commit comments