Leecode #5 ZigZag Conversion

本文解析LeetCode第6题,锯齿形字符串转换问题,详细阐述了解题思路及其实现代码。通过分析字符串在不同行数下的锯齿形排列规律,提供了完整的C++解决方案。

一、 问题描述
Leecode第六题,题目为:

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 s, int numRows);
Example 1:

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

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I

问题理解为:

锯齿形转换
编写代码,将给定字符串根据给定的行数转换成锯齿形表示:
ZigZag:锯齿形,如下图所示:
锯齿形

二、解题思路

(1)这种俺规律排列的图形,是有迹可循的,找出其中的数学规律,就可以成功的实现算法了;
(2)分析:
1、 首行和末行元素下标计算方法,首行下标:a(0,i)= 2 * n - 2 (n为i的行数)
2、中间行分类:a(i,j)
j为奇数时: 2 * (j - 1 - i)
j为偶数时: 2 * i
三、实现代码

class Solution {
public:
    string convert(string s, int j) {
       
        
        if (j <= 1 || s.length() == 0)
           return s;
 
        string res = "";
        int len = s.length();
        for (int i = 0; i < len && i < j; ++i)
        {
			int indx = i;
			res += s[indx];
 
            for (int k = 1; indx < len; ++k)
            {
                
                if (i == 0 || i == j - 1)
                {
                    indx += 2 * j - 2;
                }
                
                else
                {
                    if (k & 0x1)  
						indx += 2 * (j - 1 - i);
                    else indx += 2 * i;
                }
 
                
                if (indx < len)
                {
                    res += s[indx];
                }	
            }
        }
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值