mirror of
https://github.com/iritmaximus/tira.git
synced 2026-10-12 19:13:47 +03:00
49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
def count(s, c):
|
||
"""
|
||
Tehtäväsi on laskea, moniko merkkijonon osajono ei sisällä
|
||
kiellettyä merkkiä. Syötteenä sinulle annetaan merkkijono ja merkki,
|
||
jota osajonot eivät saa sisältää.
|
||
|
||
Voit olettaa, että merkkijono muodostuu merkeistä a–z,
|
||
siinä on enintään 105 merkkiä ja kielletty merkki on jokin merkeistä a–z.
|
||
Tavoitteena on, että algoritmin aikavaativuus on O(n).
|
||
|
||
Toteuta tiedostoon forbidden.py funktio count,
|
||
joka palauttaa halutun tuloksen.
|
||
"""
|
||
result = 0
|
||
combination = 0
|
||
prev_str = ""
|
||
|
||
# print()
|
||
# print(f"{s} --- {c}")
|
||
# print()
|
||
|
||
for char in s:
|
||
if char == c:
|
||
# print(f"forbidden char {c}")
|
||
result += combination
|
||
combination = 0
|
||
prev_str = ""
|
||
continue
|
||
|
||
if prev_str == "":
|
||
prev_str = char
|
||
combination += len(prev_str)
|
||
|
||
else:
|
||
prev_str += char
|
||
combination += len(prev_str)
|
||
|
||
# print(f"char: {char} -> prev_str: {prev_str} = {combination}")
|
||
|
||
result += combination
|
||
return result
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(count("abacabb", "b")) # 7
|
||
print(count("abcdef", "g")) # 21
|
||
print(count("xxxxxxxxx", "x")) # 0
|
||
print(count("pupujussikainen", "u")) # 48
|