give me a c++ solution for this compeitive programming problem , use a simple hash…
- User
give me a c++ solution for this compeitive programming problem , use a simple hash method : G. Take a Pair time limit per test2 s. memory limit per test256 MB Alex has a string s , made up of lowercase Latin letters.
Alex wants to remove two consecutive characters from the string s , and you are curious to find out how many unique strings can be formed by this operation.
For example, if Alex's string is "aaabcc", the possible different strings are: "abcc" (by deleting the first two or second and third characters), "aacc" (by deleting the third and fourth characters), "aaac" (by deleting the fourth and fifth characters), and "aaab" (by deleting the last two characters).
Input
The first line of the input contains a single integer t (1≤t≤104 ) — the number of test cases.
Each test case consists of two lines.
The first line contains an integer n (3≤n≤2⋅105 ) — the length of the string.
The second line contains a string s of length n , consisting of lowercase Latin letters.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅105 .
Output
For each test case, print one integer — the number of distinct strings that can be formed by removing two consecutive characters.
Example InputCopy 7 6 aaabcc 10 aaaaaaaaaa 6 abcdef 7 abacaba 6 cccfff 4 abba 5 ababa OutputCopy 4 1 5 3 3 3 1
Note
The first example is explained in the statement.
In the third example, the resulting strings are: "cdef", "adef", "abef", abcf", and "abcd".
In the seventh example, any pair of consecutive deletions will result in the string "aba".
- Assistant
To solve this problem, we can utilize a simple hash method to detect unique strings. The goal is to remove two consecutive characters from a given string and determine the number of distinct strings that can result from all possible such operations. Here's a C++ solution:
cpp - User
the problem with this solution is the space complexity, i run out of memory quickly
- Assistant
If you encounter memory issues with the approach based on storing entire strings, we can optimize the solution by avoiding storing large strings and instead focus on identifying unique pairs of consecutive characters that result in different deletion outcomes.
Here's an optimized approach that focuses on pairs of characters rather than constructing and storing whole strings: