leetcode练习题 -- 6. ZigZag Conversion

本文介绍了一种将字符串以Z形路径分布在多行上的算法,并提供了详细的实现代码。该算法适用于将任意字符串按照指定行数进行Z形排列,最终按行读取形成新的字符串。

摘要生成于 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
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".

代码如下:

class Solution {
public:
    string convert(string s, int numRows){
        if (numRows == 1)return s;	         //遇到单个字符串直接返回
        string res;
	for (int i = 0; i < numRows; i++)       //判断读入数据的位置
    	{
	    	for (int j = 0; j < s.length() + i; j += (numRows - 1) * 2) //每次按特定的规律叠加
	    	{
	    		if (i != 0 && i != numRows - 1)       //如果不是最开始和最后一行
	    		{
    				if (j - i > 0)
	      				res += s[j - i];       //存在便存入数组
	    			if (j + i < s.length())
	    				res += s[j + i];
	    		}
	    		else if (j + i < s.length())            //存入一个即可
	    			res += s[j+i];
	    	}
	    }
    	return res;
    }
};

  这个题目是让人按照锯齿图形存入数据,就是按照 Z 字存入 即:

1                               7                             13      换成字母就是      P                                 I                                N

2                  6           8                   12                                            A                    L          S                    I          G

3         5                    9         11                                                      Y          A                    H          R  

4                              10                                                                  P                                 I

这便是把convert("PAYPALISHIRING", 3)的 3 改成 4 的排列顺序,读出的结果是 PINALSIGYAHRPI

整体的思路便是一行一行读取,到下一行的时候,在上一行的基础上读入上一行数据前后的字母

以此类推 知道最后一行




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值