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.
Tried to simplify the code above and optimize a little bit by avoiding iterating over the repeatable symbols and jumping straight to the distinct by incrementing for loop counter and replacing sum with n*(n+1)/2
publicstaticlongsubstrCount(intlength,Strings){longcounter=0;for(inti=0;i<length;i++){// if the current symbol is in the middle of palindrome, e.g. abaintoffset=1;while(i-offset>=0&&i+offset<length&&s.charAt(i-offset)==s.charAt(i-1)&&s.charAt(i+offset)==s.charAt(i-1)){counter++;offset++;}// if this is repeatable characters aaintrepeats=0;while(i+1<length&&s.charAt(i)==s.charAt(i+1)){repeats++;i++;}counter+=repeats*(repeats+1)/2;}returncounter+length;}
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 →
Tried to simplify the code above and optimize a little bit by avoiding iterating over the repeatable symbols and jumping straight to the distinct by incrementing for loop counter and replacing sum with n*(n+1)/2