We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I use a deque to keep track of previous counts to find the middle cases. I like this solution because there is a single loop while most other solutions have nested loops.
fromcollectionsimportdeque# Complete the substrCount function below.defsubstrCount(n,s):current_char=Nonetotal_count=0char_count=0count_deque=deque([0,0],maxlen=2)foriinrange(n):ifs[i]==current_char:char_count+=1else:# check for middle charsifi>=3andcount_deque[1]==1ands[i-2-char_count]==current_char:middle_case_count=min([count_deque[0],char_count])total_count+=middle_case_counttotal_count+=sum(range(char_count+1))count_deque.append(char_count)current_char=s[i]char_count=1ifi>=3andcount_deque[1]==1ands[i-1-char_count]==current_char:middle_case_count=min([count_deque[0],char_count])total_count+=middle_case_counttotal_count+=sum(range(char_count+1))returntotal_count
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Special String Again
You are viewing a single comment's thread. Return to all comments →
I use a deque to keep track of previous counts to find the middle cases. I like this solution because there is a single loop while most other solutions have nested loops.