AB-string (Codeforces 1238D)
Tags: DP, combinatorics

The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings:   $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$);  $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$);  $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.

Input: The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$.The second line contains the string $$$s$$$, consisting of letters A and B.

Output: Print one integer — the number of good substrings of string $$$s$$$.

Note: In the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.

Sample Inputs:
5
AABBB

3
AAA

7
AAABABB

Sample Outputs:
6

3

15

Solution (Python):
q = int(input())
Q = input()
x1 = Q[0]
(l, r) = (1, 0)
for i in range(1, q):
    x2 = Q[i]
    if x1 == x2:
        r += i
        if l < i:
            r -= 1
        l += 1
    else:
        r += i - l
        l = 1
    x1 = x2
print(r)

Solution (Python):
n = int(input())
s = input()
res = n * (n - 1) // 2
for x in range(2):
    cur = 1
    for i in range(1, n):
        if s[i] == s[i - 1]:
            cur += 1
        else:
            res -= cur - x
            cur = 1
    s = s[::-1]
print(res)

Solution (Python):
n = int(input())
s = input()
ans = n * (n - 1) // 2
for x in range(2):
    cur = 1
    for i in range(1, n):
        if s[i] == s[i - 1]:
            cur += 1
        else:
            ans -= cur - x
            cur = 1
    s = s[::-1]
print(ans)