You should come up with some example strings and step through it using pen and paper.
Some hints/offhand observations: the ifs can't be combined, the second if can be outside the inner loop, it would be more efficient to tabulate the results and get rid of the nested loops.