How can i optimize this code

I solved the count substrings (STRSUB) problem in the march challenge 2015 but got TLE in most of the test case. How can i optimize this type of codes which have multiple loops.
here is my solution—>
http://www.codechef.com/viewsolution/6456624