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.
The __repr__ of the runs class isn't necessary, but it's useful for showing the runs that are found in the string when stepping through the function. We pad the list of runs with "empty" values at the beginning and end to prevent the need for handling edges in the next step.
We then iterate through the list of runs, considering each run as a possible candidate to be the middle of a special palindrome (e.g. aadaa). We first add the triangle number of its length to the count. If the candidate run has length 1 and its adjacent runs have the same letter, we then add the least of its adjacent runs' lengths to the count.
defsubstrCount(n,s):classrun:def__init__(self,letter:str,len:int=1):self.letter,self.len=letter,lendef__repr__(self):returnself.letter*self.len# find all runs in stringprev,runs,r='',[],run('',0)forcurrins:ifprev!=curr:runs+=[r]#padfronttopreventout-of-ranger=run(curr)else:r.len+=1prev=currruns+=[r,run('',0)]#padendtopreventout-of-range# count runs, special stringsout=0fori,r1inenumerate(runs[1:-1]):out+=r1.len*(r1.len+1)// 2 # triangle numberifr1.len==1and(r0:=runs[i]).letter==(r2:=runs[i+2]).letter:out+=min(r0.len,r2.len)#findpeak'swidthreturnout
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 →
The
__repr__
of theruns
class isn't necessary, but it's useful for showing the runs that are found in the string when stepping through the function. We pad the list of runs with "empty" values at the beginning and end to prevent the need for handling edges in the next step.We then iterate through the list of runs, considering each run as a possible candidate to be the middle of a special palindrome (e.g.
aadaa
). We first add the triangle number of its length to the count. If the candidate run has length 1 and its adjacent runs have the same letter, we then add the least of its adjacent runs' lengths to the count.