dp solution for regular matching