首先解释一下题目意思,这个ZigZag就是锯齿形,之字形,举个例子就可以明白
对于0~13当numRows=3时
0 4 8 12
1 3 5 7 9 11 13
2 6 10
当numRows=4的时候
0 6 12
1 5 7 11 13
2 4 8 10 14
3 9 15
这就是所谓的蛇皮走位,哈哈哈,然后可以看出它是有周期的,numRows = 3的时候,0~3是一个周期,numRows = 4的时候,0~5是一个周期
总体的想法是按照行,一行一行的append,除了第一行和最后一行,其他的行都会有多出来的数字,这个数字就是j+2*numRows-2*i,emmmm,其实就是找规律
最后的代码如下,但是还有一个问题,之前用ans+=来添加字符,但是显示超时,用push_back就不会超时,这是个问题,我还要去了解下他们的机制,这里先留个坑。。。
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
if(len==0||numRows<2)
return s;
string ans = "";
int size = 2*numRows-2;
for(int i = 0;i<numRows;i++)
for(int j = i;j<len;j+=size)
{
ans.push_back(s[j]);
if(i>0&&i<numRows-1)
{
int temp = j+size-2*i;
if(temp<len)
ans.push_back(s[temp]);
}
}
return ans;
}
};