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.
defsubstrCount(n,s):current_char=s[0]occurences=[[current_char,0]]# first we create a list of all occurences of letters, but we count repetitions, like for "aabaa" we would have [["a",2],["b",1],["a",2]]forcharins:ifchar==current_char:occurences[-1][1]+=1else:occurences.append([char,1])current_char=char# now we calculate specials that are from <one char> substrings - the amount is equal to (x^2+x)/2 if the length is xspecials=sum([(occurence[1]**2+occurence[1])/2foroccurenceinoccurences])# now we add the cases where there is a different char in the middleforiinrange(1,len(occurences)-1):if(occurences[i][1]==1)and(occurences[i-1][0]==occurences[i+1][0]):specials+=min(occurences[i-1][1],occurences[i+1][1])returnint(specials)
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 →