solution for beautiful strings problem