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.
staticlongsubstrCount(intn,Strings){// initialize counter to n because each character is a// palindromic stringintcounter=n;// to count consecutive characters that are the sameintconsec=1;// the middle index of a 3-character symmetry,// assigned only once detectedintmidIndex=-1;// compare with previous character so start with i=1for(inti=1;i<n;i++){if(s.charAt(i)==s.charAt(i-1)){// Condition 1: All of the characters are the same// For n consecutive characters that are the same,// we have this formula:// Number of palindromic strings =// (n-1) + (n-2) + ... + (n-(n-1))counter+=consec;consec++;// Condition 2: All characters except the middle one// are the sameif(midIndex>0){// check for symmetry on both sides// of the midIndexif((midIndex-consec)>0&&s.charAt(midIndex-consec)==s.charAt(i)){counter++;}else{// no more possibility of palindromic string// with this midIndexmidIndex=-1;}}}else{// reset consecutive chars counter to 1consec=1;// check for a 3-character symmetryif(((i-2)>=0)&&s.charAt(i-2)==s.charAt(i)){counter++;// 3-char symmetry is detected// to check if the next characters are the same// and symmetrical along the midIndexmidIndex=i-1;}else{midIndex=-1;}}}returncounter;}
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 →
Java 8
Passed all test cases