[Codewars] Coding with Squared Strings

Coding with Squared Strings

  • 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
40
41
42
43
44
45
46
#include <string>
using namespace std;
class CodeSqStrings
{
public:
static std::string code(const std::string &strng) {
int n = 1;
for(; n * n < strng.length(); n++);
vector<string> mat(n,string(n,'\v'));
for(int j = n - 1, p = 0; j >= 0 and p < strng.length(); j--) {
for(int i = 0; i < n and p < strng.length(); i++) {
mat[i][j] = strng[p++];
}
}
string res = "";
for(int i = 0; i < n; i++) {
res += mat[i];
res.push_back('\n');
}
res.pop_back();
return res;
}
static int len(const std::string &strng) {
int res = 0;
for(; res < strng.length() and strng[res] != '\n'; res++);
return res;
}
static std::string decode(const std::string &strng) {
int n = len(strng);
vector<string> mat(n,string(n,'\v'));
for(int i = 0, p = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
mat[i][j] = strng[p++];
}
p++;
}
string res = "";
for(int j = n - 1, p = 0; j >= 0 and p < strng.length(); j--) {
for(int i = 0; i < n and p < strng.length(); i++) {
res.push_back(mat[i][j]);
}
}
while(res.size() and res.back() == '\v') res.pop_back();
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/10/PS/Codewars/coding-with-squared-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.