[problem]
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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return"PAHNAPLSIIGYIR"
.
[thinking]
zigzag conversion其实就是找找规律输出字符串,个人认为没啥实用价值,多举几个例子找找规律吧。
找出每个锯齿与每个锯齿之间的规律,可以看出第一行和最后一行(RowNum)均没有斜值
,其余行的斜值与竖值之间相差2*(RowNum-行标),而不同锯齿之间的竖值相差2*(RowNum-1);
这句话引自:http://blog.csdn.net/qq_31646529/article/details/78955143
【coding】
/*
runtime: 32ms
case 1: if(numRows==1 || s.size()<=numRows) return s;
case 2: generate numRows sequences, join them sequentially, all indices less than s.size().
stepcount=(numRows-1)*2, for i= 0 to numRows-1, the ith sequence, first is s[i],
2a. for 0th and n-1 th sequence, the step equal to stepcount
2b. for other, sum of two successive step equal to stepcount,
the odd one is stepcount-(i*2), the even one is (i*2)
参考解法:https://discuss.leetcode.com/topic/20498/almost-most-simple-and-intuitive-solution-c-with-clear-algo-description
k=i<<1 表示 i 左移一位, 实际上就是 i * 2^1
k=i<<n表示 i 左移 n 位,实际上就是 i * 2^n
k=i>>n 表示 i 右移 n位,实际上就是 i / 2^n
*/
class Solution {
public:
string convert(string s, int numRows) {
if(numRows<2 || s.size() <= numRows) return s;
string res(s.size(),0);
char *p=&res[0];
for(int i=0,k,j,step=2*(numRows-1);i<numRows;i++)
{
if(i==0 || i==(numRows-1))
for(j=i;j<s.size();j+=step) *p++=s[j];
else
for(j=i,k=i<<1;j<s.size();k=step-k,j+=k) *p++=s[j];
}
return res;
}
};