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.
classGroup(NamedTuple):char:strcount:intdefsubstrCount(n,s):total=0groups=[]group=Group(char=s[0],count=1)# iterate over 's', grouping runs of same charforcharins[1:]:ifgroup.char==char:#incrementcurrentcharcountgroup=Group(char=char,count=1+group.count)else:#registercurrentgroup,restartcountw/newgroupgroups.append(group)total+=(group.count**2+group.count)// 2 # n substringsgroup=Group(char=char,count=1)#restartw/newchar# register final groupgroups.append(group)total+=(group.count**2+group.count)// 2 # n substrings in group# iterate over triplets of groups, counting# odd sized substrings w/ extra middle charforbefore,current,afterinzip(groups,groups[1:],groups[2:]):ifcurrent.count==1andbefore.char==after.char:total+=min(before.count,after.count)returntotal
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 →
(hopefully) easy-to-read O(n) Python solution