How to resolve TLE (TRAINSET)?

problem- https://www.codechef.com/problems/TRAINSET
my solution- https://www.codechef.com/viewsolution/29011583
time given -1 sec
solution time- 1.01 sec

Your solution’s complexity is O(n*s). Try solving it in O(n).
Hint: Do not iterate through all the char of string.

thanks for your suggestion.
i made changes such as using an unordered list and using .compare function yet the TLE is still there.
new solution- https://www.codechef.com/viewsolution/29012087