Smaller strings(Google kick start round c)

my solution has time complexity of O(n*k)
k = first k characters from a to z
n = size of string
but solution got TLE
how to optimize it?
link to the question and my solution:

https://www.codechef.com/viewsolution/46839080

thanks in advance