bheeshm
bheeshm

Reputation: 3

Reverse C++ vector<char>

I am not that great in C++. Question is a simple reverse string. This is a Leetcode question and I am trying to solve it recursively.

void reverse_str(vector<char>& s, int len)
{
   if (len <= 1) return;
        
   swap(s[0], s[len-1]);
   reverse_str(s.front(), len-2);  // Compilation error when I call s.front()
}

void reverseString(vector<char>& s)
{
    reverse_str(s, s.size());
}

I am trying to recursively call reverse_str with the reference to the 2nd element in the vector. How do I do that?

Thank You in advance.

Upvotes: 0

Views: 727

Answers (2)

Roshan M
Roshan M

Reputation: 601

You can do that in this way

void reverse_str(vector<char>& s, int len = 0) // default params with zero
{ 
    int n = s.size(); 
    if (len == n / 2) 
        return; 
// swap last with first upto n/2
    swap(s[len ], s[n - len - 1]); 
    reverse_str(s, len + 1); 
} 
  
void reverseString(vector<char>& s)
{
    reverse_str(s);
}

Upvotes: 1

Emma
Emma

Reputation: 27723

Maybe we'd move std::swap to the helper function and recurse the helper:

// The following block might trivially improve the exec time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
    return 0;
}();


// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <algorithm>


static const struct Solution {
    using ValueType = std::int_fast16_t;
    static constexpr void reverseString(
        vector<char>& s
    ) {
        helper(s, 0, std::size(s) - 1);
    }

    static constexpr void helper(
        std::vector<char>& s,
        ValueType left,
        ValueType right
    ) {
        if (left >= right) {
            return;
        }

        std::swap(s[left], s[right]);
        ++left;
        --right;
        helper(s, left, right);
    }
};

We can also use unsigned int:

// The following block might trivially improve the exec time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
    return 0;
}();


// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <algorithm>


static const struct Solution {
    using ValueType = std::uint_fast16_t;
    static constexpr void reverseString(
        vector<char>& s
    ) {
        if (s.empty()) {
            return;
        }

        helper(s, 0, std::size(s) - 1);
    }

    static constexpr void helper(
        std::vector<char>& s,
        ValueType left,
        ValueType right
    ) {
        if (left >= right) {
            return;
        }

        std::swap(s[left], s[right]);
        ++left;
        --right;
        helper(s, left, right);
    }
};

Upvotes: 0

Related Questions