algos_and_structures/algocode/two_pointers/urlify.py

51 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Дан список s, представляющий URL-адрес (буквы и пробелы). Нужно заменить все пробелы в первых k символах на %20, используя свободное место в конце списка и вернуть изменённый список s в качестве ответа.
Пример 1:
Ввод: s = ["h","e","l","l","o"," ","w","o","r","l","d","#","#"], k = 11
Вывод: ["h","e","l","l","o","%","2","0","w","o","r","l","d"]
Пример 2:
Ввод: s = ["a"," ","b"," ", " ", "c","#","#","#","#","#","#"], k = 6
Вывод: ["a","%","2","0","b","%","2","0","%","2","0", "c"]
Ограничения:
len(s) >= 1
"""
from typing import List
def solve(s: List[str], k: int) -> List[str]:
fast = len(s) - 1
slow = k - 1
while slow >= 0:
# Если у нас не пробел
if not s[slow] == " ":
s[fast] = s[slow]
fast -= 1
slow -= 1
# Если пробел
else:
s[fast] = "0"
s[fast-1] = "2"
s[fast-2] = "%"
fast -= 3
slow -= 1
print(s)
solve(s = ["h","e","l","l","o"," ","w","o","r","l","d","#","#"], k = 11)
# Вывод: ["h","e","l","l","o","%","2","0","w","o","r","l","d"]
solve(s = ["a"," ","b"," ", " ", "c","#","#","#","#","#","#"], k = 6)
# Вывод: ["a","%","2","0","b","%","2","0","%","2","0", "c"]
# 0 1 2 3 4 5 6 7 8 9 10 11 12
# "h","e","l","l","o"," ","w","o","r","l","d","#","#"
# s f
#
# 0 1 2 3 4 5 6 7 8 9 10 11 12
# "a"," ","b"," "," ","c","#","#","#","#","#","#"
# s