ZigZag Conversion

[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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

佳悦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值