本题链接:https://leetcode-cn.com/problems/zigzag-conversion/
这题一开始看到的时候毫无头绪,后来思考了一会儿,这才发现其中的关键
官方解答提供了两种方法,我的算法类似于性能较优的那一个,官网给的那段代码我在debug时遇到错误,不知道咋解决,这里只放我自己的代码,也比较直观
#include <bits/stdc++.h>
using namespace std;
/* 该算法重点在于关注元素之间的距离
特殊情况,numRows==1 时,直接返回原字符串即可
*/
class Solution
{
public:
string convert(string s, int numRows)
{
string str = "";
if(1 == numRows)
{
return s;
}
int step = (numRows - 1) * 2;
int len = s.length();
int len2 = (len + step - 1) / step; // 第一个数组的长度
for(int i = 0; i < numRows; i++)
{
int offset = (numRows - i - 1) * 2;
if(offset == step || numRows - 1 == i)
{
for(int j = i; j < len; j += step)
{
str += s[j];
}
}
else
{
str += s[i];
for(int j = i; j < len; j += step)
{
if(j + offset < len)
{
str += s[j + offset];
}
if(j + step <len)
{
str += s[j + step];
}
}
}
}
return str;
}
};
int main()
{
Solution sol;
cout<<sol.convert("LEETCODEISHIRING", 3)<<endl; // "LCIRETOESIIGEDHN"
cout<<sol.convert("LEETCODEISHIRING", 4)<<endl; // "LDREOEIIECIHNTSG"
cout<<sol.convert("", 1)<<endl;
return 0;
}