s0006
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sainnhe Park 2022-11-02 20:19:54 +08:00
parent a12d393198
commit 83c66fc158
3 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,20 @@
#ifndef S0006_ZIGZAG_CONVERSION
#define S0006_ZIGZAG_CONVERSION
#include <string>
using namespace std;
class Solution {
public:
/**
* @brief Zigzag Conversion
*
* @param s the string to be converted
* @param numRows rows
* @return converted string
*/
string convert(string s, int numRows);
};
#endif

View File

@ -0,0 +1,51 @@
#include "s0006_zigzag_conversion.hpp"
// 简单地找规律
// n = 3
// 0 4 8 12 2*(n-1) * col
// 1 3 5 ... (n-1) * col + 1
// 2 6 10 2*(n-1) * col + (n-1)
// n = 4
// 0 6 12 2*(n-1)*col
// 1 5 7 11 2*(n-1)*col+row, 2*(n-1)*col-row
// 2 4 8 10 2*(n-1)*col+row, 2*(n-1)*col-row
// 3 9 2*(n-1)*col + (n-1)
string Solution::convert(string s, int numRows) {
string r = "";
int l = s.length();
if (l == 1 || numRows == 1) {
return s;
}
for (int col = 0; 2 * (numRows - 1) * col < l; col++) {
r += s[2 * (numRows - 1) * col];
}
if (numRows >= 3) {
for (int row = 1; row < numRows - 1; row++) {
for (int col = 0;; col++) {
if (col == 0) {
if (2 * (numRows - 1) * col + row < l) {
r += s[2 * (numRows - 1) * col + row];
}
} else {
if (2 * (numRows - 1) * col - row < l) {
r += s[2 * (numRows - 1) * col - row];
} else {
break;
}
if (2 * (numRows - 1) * col + row < l) {
r += s[2 * (numRows - 1) * col + row];
} else {
break;
}
}
}
}
}
for (int col = 0; 2 * (numRows - 1) * col + (numRows - 1) < l; col++) {
r += s[2 * (numRows - 1) * col + (numRows - 1)];
}
return r;
}

View File

@ -0,0 +1,27 @@
#include "s0006_zigzag_conversion.hpp"
#include <gtest/gtest.h>
TEST(Problem6, Case1) {
string s("PAYPALISHIRING");
int rows = 3;
string r("PAHNAPLSIIGYIR");
Solution solution;
EXPECT_TRUE(solution.convert(s, rows) == r);
}
TEST(Problem6, Case2) {
string s("PAYPALISHIRING");
int rows = 4;
string r("PINALSIGYAHRPI");
Solution solution;
EXPECT_TRUE(solution.convert(s, rows) == r);
}
TEST(Problem6, Case3) {
string s("AB");
int rows = 4;
string r("AB");
Solution solution;
EXPECT_TRUE(solution.convert(s, rows) == r);
}