:heavy_check_mark: ランレングス圧縮 (String/run_length_encode.hpp)

ランレングス圧縮

連続する同じ要素をまとめて、要素とその出現回数のペア列に変換します。

run_length_encode

template <typename Container>
vector<pair<typename Container::value_type, int>> run_length_encode(const Container &v)

連続する同一要素を1つのペアにまとめ、元のコンテナを走査して圧縮されたペア列を返します。

計算量

  • $O(n)$

Verified with

Code

#include <bits/stdc++.h>
using namespace std;

template <typename Container>
vector<pair<typename Container::value_type, int>> run_length_encode(const Container &v)
{
    using T = typename Container::value_type;
    vector<pair<T, int>> result;

    for (const auto &n : v)
    {
        if (result.empty() || result.back().first != n)
        {
            result.push_back({n, 0});
        }

        result.back().second++;
    }

    return result;
}
#line 1 "String/run_length_encode.hpp"
#include <bits/stdc++.h>
using namespace std;

template <typename Container>
vector<pair<typename Container::value_type, int>> run_length_encode(const Container &v)
{
    using T = typename Container::value_type;
    vector<pair<T, int>> result;

    for (const auto &n : v)
    {
        if (result.empty() || result.back().first != n)
        {
            result.push_back({n, 0});
        }

        result.back().second++;
    }

    return result;
}
Back to top page