Files
2023-11-07 01:27:43 +02:00

49 lines
1.3 KiB
Python
Raw Permalink 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.
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