leetcode ZigZag Conversion

本文介绍了一种将字符串以Zigzag形式排列并按行读取的算法实现。通过分析字符位置规律,该算法能将输入字符串如'PAYPALISHIRING',在指定的行数中以Zigzag模式排列,再逐行读取转换为'PAHNAPLSIIGYIR'。特别针对不同行数的情况进行了详细的解析,并提供了完整的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)

这里写图片描述
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”.

很明显我们可以通过分析转换前字符和转换后字符的规律来解决问题。
对于第1行和第numRows行,字符在原字符串的下标index=index+2*(numRows-1)
对于第i行(非第一行和非第numRows行),则要分为奇数列和偶数列分别处理。
当为奇数列时,index += 2*(numRows-i-1)
当为偶数列时,index += 2*i

class Solution {
public:
    string convert(string s, int numRows) {
        int i;
        i=0;
        string res="";
        int len = s.length();

        if(numRows <=1 || len <2)
            return s;
        if(numRows > len)
            return s;

        for(i=0;i<numRows;i++)
        {
            int index;
            index = i;
            res += s[index];
            int k;
            for(k=1;index<len;k++)
            {
                if(i==0 || i==numRows-1)
                    index += 2*(numRows-1);
                else 
                {
                    if(k&0x1 == 1)
                        index+=2*(numRows-i-1);
                    else
                        index+=2*i;
                }

                if(index<len)
                    res += s[index];
            }
        }
        return res;
    }
};

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值