Getting TLE in CHEFSHIP May Cook-off 2020

I think i have use the substr in best possible way , but still got the TLE in CHEFSHIP.
it would be great if someone could give a look at my code.
Problem CHEFSHIP link
My submission is here.