Can someone tell me the error in this code

Question: https://codeforces.com/problemset/problem/701/C
My solution: https://ideone.com/Ps7R0N

Your code fails for the test case
13
aaBCCeBdAaeCc

Expected output:
7

Your output:
9

I couldn’t rectify your code without altering your approach but this is where you code goes wrong.
The map that you’re creating maps input as follows: aaBCCeBdAaeCc
Now the letters in bold would hold their indexes in your final map and as you can see Ce at 4,5 can be replace with eC at 10,11 but your loop fails to do so
Hence, you get 9 instead of 7

You might wanna change your approach instead.
Do share your code once it’s accepted.

Hope this helps.

Thanks @a_d_i I understood now why my approach was wrong.
I tried a different approach and it got accepted.
Code: https://ideone.com/hjEBaL