简体   繁体   中英

Count all the occurrences of the prefix string

Find the alphabet present at that location and determine the no of occurrences of the same alphabet preceding that location n .

Input:

length = 9

string = "abababbsa"

n = 9

Output:

3

Explanation:

Find the alphabet at nth position 9 ie a . Count all the occurrences before that index which is 3 .

Code:

length = int(input())
string = list(input())
n = int(input())
str1 = string[n-1]
print(string[0:n-1].count(str1))

The above code gives TLE. How can I optimize this?

Well It becomes easy if you use re ( regex )

import re
length = int(input())
my_string = input('Enter your string')
n = int(input())
print(len(re.findall(my_string[n-1],my_string[:n-1])))

So what is happening is we are finding all occurences of the character before n by slicing the string at n-1 and just getting the length of the list ( all occurences ).

One way to optimize is to use string as usual in spite of converting it into a list:

string = input()

The complexity would now be O(n) where n is the input position, whereas, in your case, because the string was explicitly converted to list, the complexity was O(length of the string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM