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;
}
};
}
本文详细介绍了如何实现LeetCode上的ZigZag Conversion算法题,该题要求将输入字符串以Z字形方式分布于指定行数上,再按行读取形成新的字符串。通过C++代码示例,讲解了算法的实现过程,包括错误处理和特殊情况的考虑。
871

被折叠的 条评论
为什么被折叠?



