题目描述
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
示例 1:
输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
示例3:
输入:s = “A”, numRows = 1
输出:“A”
解法
我的解法
寻找下标和行号之间的关系
结果显示数组内存分配错误的问题
class Solution {
public:
string convert(string s, int numRows) {
int num = numRows - 2;// 中间斜着的部分应该有几行
int h = num + numRows;// 一轮包含多少个元素
int i = 0;
//声明行数个字符串
vector<string> str(numRows,"");
if(numRows==1)
{
return s;
}
else if(numRows==2)
{
string s1="";
string s2="";
while(i!=s.size())
{
if(i%2!=0)
{
s1=s1+s[i];
}
else
{
s2 = s2 + s[i];
}
i++;
}
return s1+s2;
}
else
{
int n=0;
//遍历字符串
while(i!=s.size())
{
if(i%h<i/h+numRows)
{
str[i%h] = str[i%h] + s[i];
}
else if(i%h==i/h+numRows)
{
str[i%h] = str[i%h] + s[i];
n = 0;
}
else
{
str[i%h-2-2*n] = str[i%h-2-2*n] + s[i];
n++;
}
i++;
}
string result="";
for(int j=0;j<numRows;j++)
{
result=result+str[j];
}
return result;
}
}
};
力扣解法
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
// 取最小值没想到
vector<string> rows(min(numRows, int(s.size())));
int curRow = 0;
// 控制前进方向
bool goingDown = false;
// 字符串遍历可以采用 for(char c:s)的形式
for (char c : s) {
rows[curRow] += c;
// 改变前进方向的节点有两种
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
// 这个做法很巧妙,不向下行数就直接减1
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) ret += row;
return ret;
}
};