Short Palindrome Discussions | | HackerRank

Short Palindrome

  • + 0 comments

    This task is the last one for me in the Program of the 3-Month Preparation Kit. Good luck to everyone!

    Java O(n)

    public static int shortPalindrome(String s) {
                int MOD = 1_000_000_007;
                int n = s.length();
                
                long[] singleCount = new long[26];
                long[][] pairCount = new long[26][26];
                long[] tripletCount = new long[26];
                
                long palindromeCount = 0;
    
                for (char ch : s.toCharArray()) {
                    int charIndex = ch - 'a';
    
                    palindromeCount = (palindromeCount + tripletCount[charIndex]) % MOD;
    
                    for (int i = 0; i < 26; i++) {
                        tripletCount[i] = (tripletCount[i] + pairCount[i][charIndex]) % MOD;
                    }
    
                    for (int i = 0; i < 26; i++) {
                        pairCount[i][charIndex] = (pairCount[i][charIndex] + singleCount[i]) % MOD;
                    }
    
                    singleCount[charIndex] = (singleCount[charIndex] + 1) % MOD;
                }
    
                return (int) palindromeCount;
            }