improve algorithm for key sequence matching