0

Given a string we have to output the string in a special way.

• If the string consists of one char, we output that char normally.

• Otherwise, we divide the string into two equal parts (if the number of letters in the substr is odd, the second part of the substr will be one letter longer than the first), and we output the first part twice and then the second part (according to the same rules).

For example, let's assume that we want to output the string YOGURT. We divide that string into two equal parts: YOG and URT.

How will we output the substr YOG? Again, it will be divided into two parts - Y and OG. The substr Y we output normally (but in the output of the substr YOG we will do it twice), and the substr OG we output as OOG. So the substr YOG we output as YYOOG.

Analogously, the substr URT is going to give the output UURRT. So the string YOGURT is going to be output as YYOOGYYOOGUURRT.

Length of the string can at max be 10000.

Now I tried using a non recursion way to solve this problem but it was way to slow so I have come to an conclusion I have to do this with recursion. And since I don't have that much experience with recursion I would really need some help.

  • 2
    By "we" the assigner of this task likely means "you." We, meaning stackoverflow, have no problem helping people with their code, but in order to do that, there needs to be code. My recommendation: Break the task down into smaller subtasks and attack each task separately. If you're still stuck, recurse. Break the subtasks down into even smaller tasks. – user4581301 Dec 21 '22 at 19:22
  • 1
    You wrote some code that you determined is slow. So you should show that code and we can probably point out what you did wrong. That would be a far better start than you deciding you need to do it recursively and asking someone to write it from scratch. If it turns out that recursion is appropriate then someone might point out how you should adapt your solution to that. But right now, you have nothing to show. – paddy Dec 21 '22 at 19:25

1 Answers1

1

This is very naturally implemented with recursion like so:

void print(std::string_view s) {
    if (s.size() <= 1) std::cout << s;
    else {
        auto m = s.size() / 2;
        print(s.substr(0, m));
        print(s.substr(0, m));
        print(s.substr(m));
    }
}
paddy
  • 60,864
  • 6
  • 61
  • 103
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • To make this function more robust, consider testing `s.size() < 2` so that it does not overflow the stack when called with empty string. Also, `std::string_view` is a drop-in replacement for `std::string` here and would mean no string copies take place. – paddy Dec 21 '22 at 19:34