Not necessarily optimal, but perhaps the easiest and most reusable:
Create a generic CircularBuffer<T> container.
This takes one parameter in constructor N , the maximum number of elements in the buffer.
The class has an array T with elements N and an index variable i , holding the index of the last added value, initializing it to -1.
CircularBuffer has two methods: Add(T ) and ToString( ).
The Add method increments i , wraps it to 0 if i = N and stores the value at the appropriate position in the array. This should allow you to add values to the buffer, storing only N in memory.
ToString will output a string equivalent to the one stored in the buffer.
For N = 4, let's say you have this array:
abcd the indices are 0 1 2 3 the last added value is ^ `ToString` should return 'dabc'
Wrapper logic is an exercise for the user.
Each time you press a key, add it to the ring buffer, call its ToString method, and see if it contains the sequences you are looking for.
source share