Substring removal

https://codeforces.com/contest/1096/problem/B
How to solve this question could someone give me a hint?

HINT:
Lets break the problem in two cases:

  1. First and last character are different.
  2. First and last character are same.

CASE 1:
For eg: aaabcdeff
You can remove substring from index: [1,8], [2,8], [3,8] (3 substrings for starting a’s) and [0,7], [0,6] (2 substrings for ending f’s), and one last case to remove entire string [0,8]. So answer is 6 or (3+2+1).
Note 3= freq of ‘a’, 2= freq of ‘f’, and +1 for empty.

CASE 2:
For eg: aaabcdeaa
Answer: ((3+1)*(2+1)=12)
Try thinking this case, and do let me know in case of further issues.

Thanks I understood this question now.