版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/darkrabbit/article/details/82791017
LeetCode Algorithm 0006 - ZigZag Conversion (Medium)
Problem Link: https://leetcode.com/problems/zigzag-conversion/description/
Description
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Solution C++
#pragma once
#include "pch.h"
// Problem: https://leetcode.com/problems/zigzag-conversion/description/
namespace P6ZigZagConversion
{
class Solution
{
public:
string convert(string s, int numRows)
{
if (numRows < 1)
{
logic_error e = logic_error("`numRows` must be greater than zero.");
throw e;
}
if (numRows == 1)
{
return s;
}
vector<string> lines = vector<string>(numRows, "");
bool add = true;
for (size_t i = 0, li = 0; i < s.size(); i++)
{
lines[li].push_back(s[i]);
li = add ? li + 1 : li - 1;
if (li == numRows || li == -1)
{
li = add ? numRows - 2 : 1;
add = !add;
}
}
string result = "";
for (vector<string>::iterator it = lines.begin(); it != lines.end(); it++)
{
result += *it;
}
return result;
}
};
}