6. ZigZag Conversion

6. ZigZag Conversion
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”.

所谓的zigzag pattern型就是指,我们以倒N型的顺序来读数。
三行的情况:
三行的情况
四行的情况:
四行的情况
我们输入的text是以这种模式来排布的,之后我们需要将其以横向的、从左到右的、我们习惯的阅读方式来从新排布,将其输出。

一种解题思路就是,我们使用数个字符串(设为row[n]),存下每一行的字符,最后将每行的字符串叠连起来,就是我们想要的结果。以一次下、一次上为一个单元(一共2*nRows-2个字符),这样我们就能算出每个输入的text中的每个字符分别对应某个单元的第几个字符,也就可以计算得到改字符的行数。也就是说,我们能够计算出text[i],text的第i个字符是属于第几行的,之后将其添加到row中。这样,我们只需要走一次text,就能够得到每行依此有哪些字符,之后将其首尾相连,得到的就是输出了。

参考代码如下:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        if(len <= 1 || numRows == 1)
            return s;
        string temp[numRows];
        for(int i = 0; i < numRows; i++)
            temp[i] = "";
        for(int i = 0; i < len; i++) {
            int index = i % (2*numRows-2);
            if(index >= numRows)
                index = 2 * numRows - 2 - index;
            temp[index] += s[i];
        }
        string result = "";
        for(int i = 0; i < numRows; i++)
            result += temp[i];
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值