LeetCode第六题:ZigZag Conversion(C++)图文详解

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)
在这里插入图片描述
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 s, int numRows);

Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
在这里插入图片描述

其原理就是呈左侧的Z型排列字符串,根据行数的不同,呈现大小不同的Z型字符串,如下分别是行数为3和4时的Z型排列:
在这里插入图片描述
图一:行数为三
在这里插入图片描述
图二:行数为四

解题思路:
根据图一和图二可推算出如下信息:
1.图一中首行P和A字符相隔2 X 3 - 2;
2.图二中首行字符P和I相隔2 X 4 - 2;
可得非斜线字符公式:2*行数 - 2;
3.图一中圆圈标注的字符P位置信息:1 + 2 X 3 - 2 - 2 X 1 = 3;
4.图二中圆圈标注的字符L位置信息:1 + 2 X 4 -2 - 2 X 1 = 5;
为说明斜线计算公式:图二斜线处A位置信息:2 + 2 X 4 -2 - 2 X 2 = 4;
可得斜线字符公式:当前列j+(2*行数-2)-2i(i是行数)不适用于首行

具体代码如下:

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1) 
        {
            return s;
        }
        string result = "";
        int size = 2 * numRows - 2;
        for (int i = 0; i < numRows; ++i) 
        {
            for (int j = i; j < s.size(); j += size) 
            {
                result += s[j];
                int tmp = j + size - 2 * i;//for循环中j=i,注意此处
                if (i != 0 && i != numRows - 1 && tmp < s.size())//首行除外,首行不包含斜线元素 
                {
                    result += s[tmp];
                }
            }
        }
        return result;
    }
};

性能:
在这里插入图片描述
总结:
1.斜线位置计算公式不包含第一行;
2.斜线计算公式中j=i,切记。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值