题目
给定一个字符类型的数组chars,chars右半区全是空字符,左半区不含空字符。现在想将左半区所有空格替换为’%20’,假设右半区足够大,请完成替换函数。
如左半区’a_b___c’ -> ‘a%20b%20%20%20c’
思路
算出替换后的最右边位置,从右往左替换。
实现
def replace(s):
chars = list(s)
n = chars.count(' ')
chars += [None] * n * 2
right = len(chars) - 1
left = len(s) - 1
while left >= 0:
if chars[left] == ' ':
chars[right-2], chars[right-1], chars[right] = '%', '2', '0'
right -= 3
else:
chars[right] = chars[left]
right -= 1
left -= 1
return ''.join(chars)
测试
def test_replace():
for _ in range(100):
size = random.randint(0, 36)
chars = random.sample(string.ascii_letters + string.digits, size)
for __ in range(size):
pos = random.randint(0, len(chars))
chars = chars[:pos] + [' '] + chars[pos:]
s = ''.join(chars)
result1 = replace(s)
result2 = re.sub(r' ', '%20', s)
result3 = s.replace(' ', '%20')
assert(result1 == result2)
assert(result2 == result3)
print('done')
测试2
补充题目
给定一个字符数组chars,其中只含数字字符和’*’,想把所有’*'移到左边,完成调整函数。
思路
从右向左完成调整。
实现
def modify(s):
chars = list(s)
left = len(s) - 1
right = left
while left >= 0:
if chars[left] != '*':
chars[right] = chars[left]
right -= 1
left -= 1
while right >= 0:
chars[right] = '*'
right -= 1
return ''.join(chars)
测试
def test_modify():
for _ in range(100):
size = random.randint(0, 100)
chars = []
for __ in range(size):
chars += random.choice(string.digits)
for __ in range(size):
pos = random.randint(0, len(chars))
chars = chars[:pos] + ['*'] + chars[pos:]
s = ''.join(chars)
result = modify(s)
assert(s.count('*') == result.count('*'))
assert(s.replace('*', '') == result.replace('*', ''))
print('done')
测试2
来源:CSDN
作者:孤舟钓客
链接:https://blog.csdn.net/guzhou_diaoke/article/details/103940823