You are given a string consisting of lowercase Latin letters. You have to select a substring say and prefix say from of equal length.
Your task is to concatenate them such that one of them is appended in reverse order and form a string that is either:
- or , here operator denotes concatenation
If string is a palindrome, then it is said to be a special palindrome.
Find the number of strings such that there exists a prefix using which a special palindrome string can be formed.
Example:
Input: n=5, str="abcde"
Output: 5
Approach
Java
public class SpecialPalindromes {public static void main(String[] args) {int n = 5;String str = "abcde";char[] s = str.toCharArray();int[] lps = KMP(s);long cnt[] = new long[n];for (int i = 0; i < n; ++i) {++cnt[lps[i]];}long ans = 0;for (int i = n - 1; i > 0; --i) {cnt[lps[i - 1]] += cnt[i];ans += cnt[i];}System.out.println(n + ans);}static int[] KMP(char[] t) {int m = t.length;int lps[] = new int[m];int i = 1;int l = 0;while (i < m) {if (t[i] == t[l]) {++l;lps[i] = l;++i;} else if (l > 0) {l = lps[l - 1];} else {++i;}}return lps;}}
No comments:
Post a Comment