Write a recursive function to solve a string manipulation problem, and discuss how you would optimize it to prevent stack overflow errors.