[Codewars] Burrows-Wheeler-Transformation

Burrows-Wheeler-Transformation

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <algorithm>
#include <string>
#include <vector>

std::pair<std::string, int> encode(std::string s) {
if (s.empty()) return {"", 0};
std::vector<std::string> l;
for (int i = 0; i < s.length(); ++i) {
l.push_back(s.substr(s.length() - i, i) + s.substr(0, s.length() - i));
}
std::sort(l.begin(), l.end());
int idx = 0;
for (int i = 0; i < l.size(); ++i) {
if (l[i] == s) {
idx = i;
break;
}
}
std::string res;
for (const auto& x : l) {
res += x.back();
}
return {res, idx};
}

std::string decode(std::string s, int n) {
if (s.empty()) {
return s;
}
std::vector<std::string> l(s.length());
for (int i = 0; i < s.length(); ++i) {
for (int j = 0; j < s.length(); ++j) {
l[j] = s[j] + l[j];
}
std::sort(l.begin(), l.end());
}
return l[n];
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/02/PS/Codewars/Burrows-Wheeler-Transformation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.