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.
publicstaticintshortPalindrome(Strings){// Write your code hereintn=s.length();finalintNUM_OF_CHARs=26;finallongMOD=1000*1000*1000+7;longres=0;long[]charsCount=newlong[NUM_OF_CHARs];long[][]pairsCount=newlong[NUM_OF_CHARs][NUM_OF_CHARs];long[]trippletsCount=newlong[NUM_OF_CHARs];for(inti=0;i<n;i++){charc=s.charAt(i);intcIdx=(int)(c-'a');//in the last turn, the pattern was '*' 'c' 'c'//this turn's pattern turns into 'c' '*' '*' //another 'c' is needed to complete the palindrome of 4 chars//so if current char satisfies, include the count of 'c' '*' '*' res=(res+trippletsCount[cIdx])%MOD;for(intj=0;j<NUM_OF_CHARs;j++){//below line usage should be to keep tab on '*' 'c' 'c' tripllets//it depends on pairsCount which monitors '*''c'trippletsCount[j]=(trippletsCount[j]+pairsCount[j][cIdx])%MOD;//this pairsCount means finding pairs that are '*''c' ('c' as in currently parsing char)//this depends on the preceeding '*', not 'c' //therefore it should be delay 1 turn, hence placed before charsCount updatepairsCount[j][cIdx]=(pairsCount[j][cIdx]+charsCount[j])%MOD;}//this charsCount is straight forward, //it is to track frequency of appeared CURRENT characters 'c'charsCount[cIdx]++;}return(int)(res%MOD);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Short Palindrome
You are viewing a single comment's thread. Return to all comments →
Java8, taking codes from Mr. MohitJain https://www.quora.com/Can-anyone-help-me-in-Solving-Short-Palindrome-from-World-Codesprint-5/answer/Mohit-Jain-247