A string game- time limit exceeded

On running this code I get time limit exceeded. Could someone please help me optimize this code.
http://www.codechef.com/viewsolution/3907244

www.redoley.com