反向 C++ 向量<char>

Reverse C++ vector<char>

我在 C++ 方面不是很好。问题是一个简单的反向字符串。这是一个 Leetcode 问题,我正在尝试递归解决它。

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());
}

我正在尝试通过引用向量中的第二个元素递归调用 reverse_str。我该怎么做?

提前谢谢你。

也许我们会 std::swap 移动到辅助函数并递归辅助函数:

// 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);
    }
};

我们也可以使用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);
    }
};

你可以这样做

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);
}