Solution for Beautiful Strings problem