[LeetCode]ZigZag Conversion

本文介绍了一种将字符串以ZigZag形式分布到多行再按行读取的算法实现,通过分析ZigZag字符串的规律,提供了一段C++代码示例,并讨论了特殊场景下的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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".


[LeetCode Source]

思路:找出ZigZag字符串的规律。

比如s长度为20,rows为5. 每个大间隔为2*rows-2,如果中间有插入值的话,插入2*rows-2-2*i(i为当前行数,0开始计数)。

写时注意几个特例可以加快速度,比如rows比字符串大,或者rows为1时直接返回字符串。

特别注意的是我编程中犯了一个错误,就是把负数和s.size()作比较。

要注意s.size()是size_t型的,unsigned int型的如果用负数做比较那么先会把int转换成size_t,这样负数(最高位为1)永远比s.size()大,最好的方法是先用一个int型存储字符串长度,或者避免负数作比较。

0                       8 16

1                7     9 15 17

2           6 10 14 18

3       5 11 13 19

4                     12 20

class Solution {
public:
    string convert(string s, int numRows) {
        int gap = numRows*2-2;
        int length = s.size();
        string ret;
        int index = 0;
        if(numRows==1)
            return s;
        if(length<=numRows)
            return s;
        for(int i=0; i<numRows; ++i){
            index = i;
            if(i==0||i==numRows-1){
                while(index<length){
                    ret += s[index];
                    index += gap;
                }
            }
            else{
                 while(true){
                    if((index - 2*i)>=length)
                        break;
                    if((index-2*i)>0&&(index-2*i)<length)
                        ret += s[index-2*i];
                    if(index<s.size())
                        ret += s[index];
                    index += gap;
                }
            }
        }
        return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值