mirror of
https://github.com/iritmaximus/tira.git
synced 2026-10-12 19:13:47 +03:00
55 lines
1.4 KiB
Python
55 lines
1.4 KiB
Python
def count(s):
|
||
"""
|
||
Tehtäväsi on laskea, monessako merkkijonon osajonossa jokainen
|
||
merkki on sama. Esimerkiksi merkkijonossa abbbcaa tällaiset osajonot ovat
|
||
|
||
a (kolmesti)
|
||
aa
|
||
b (kolmesti)
|
||
bb (kahdesti)
|
||
bbb
|
||
c
|
||
|
||
eli yhteensä 11 osajonoa.
|
||
|
||
Voit olettaa, että merkkijono muodostuu merkeistä a–z ja siinä on
|
||
enintään 105 merkkiä. Tavoitteena on, että algoritmin
|
||
aikavaativuus on O(n).
|
||
|
||
Toteuta tiedostoon onechar.py funktio count,
|
||
joka palauttaa halutun tuloksen.
|
||
"""
|
||
prev_char = ""
|
||
total = 0
|
||
for char in s:
|
||
if prev_char == "":
|
||
prev_char = char
|
||
print(
|
||
f"{total} + {s.count(char)} = {total + s.count(char)} --- {char} -> {prev_char}"
|
||
)
|
||
total += s.count(char)
|
||
|
||
elif prev_char[0] == char:
|
||
prev_char += char
|
||
print(
|
||
f"{total} + {s.count(prev_char)} = {total + s.count(prev_char)} --- {char} -> {prev_char}"
|
||
)
|
||
total += s.count(prev_char)
|
||
|
||
elif prev_char != char:
|
||
prev_char = char
|
||
print(
|
||
f"{total} + {s.count(char)} = {total + s.count(char)} --- {char} -> {prev_char}"
|
||
)
|
||
total += s.count(char)
|
||
|
||
print(s)
|
||
|
||
return total
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(count("aaa")) # 6
|
||
print(count("abbbcaa")) # 11
|
||
print(count("abcde")) # 5
|