4 - zig-zag conversion

本文介绍了一种将字符串以Z字形排列并按行读取的算法实现。该算法适用于给定行数的情况,通过计算每行字符的位置来重组字符串。文章提供了完整的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   0   4   8     12
A P L S I I G   1 3 5 7 9  11 13 
Y   I   R       2   6   10
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" .


solution: 正如我们所见,关键之处在于计算(2*nRows -2)的值,姑且命名为zzsize,每一行的红色数字的差值正好为这个值,在中间(nRows-2)行中,我们除了插入这些值外,还需要插入黑色的数字(如图),其下标由前一个数字(index)和当前行数(row)决定,大小应为(index + zzsize - 2 * row)。



class Solution {
public:
    string convert(string s, int nRows) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if( nRows <= 0)
            return NULL;
        else if(nRows == 1)
            return s;
        
        string result = "";
        int length = s.length();
        int zzSize = 2 * nRows - 2;
        
        for(int row = 0; row < nRows; row ++)
        {
            int index = row;
            while(index < length)
            {

                result = result + s.at(index);
                if(row > 0 && row < nRows - 1)
                {
                    int index2 = index + zzSize - 2 * row;
                    if(index2 < length)
                        result = result + s.at(index2);
                }
                index += zzSize;
            }
        }
        
        
        
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值