leetcode Z 字形变换 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

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

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"

示例 2:

输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P     I    N
A   L S  I G
Y A   H R
P     I

示例 3:

输入:s = "A", numRows = 1
输出:"A"

提示:
1 <= s.length <= 1000
s 由英文字母(小写和大写)、’,’ 和 ‘.’ 组成
1 <= numRows <= 1000

c++代码

class Solution {
    
    
public:
    string convert(string s, int numRows) {
    
    
    string ns = "";
    if (numRows == 1 || numRows >= s.size())return s;
    int d = numRows * 2 - 2;//d表示一个循环的串的大小
    bool bo = true;
    for (int i = 0; i < numRows; i++)
    {
    
    
        int h = i;//h表示位置
        int x = 0;//x用来判断单双数,控制每次的增加区间
        int bian= 0;//bian是每次增加的区间的大小
		while (h < s.length()) {
    
    
			if (bo == true)ns += s[h];//将对应的字符加到目标字符串尾部
			if (x % 2 == 0) {
    
    
				bian = d - 2 * i;
				if (bian == 0)bian = numRows * 2 - 2;
				h += bian;
				bo = true;
			}
			else{
    
    
				bian = d - bian;
				if (bian <= 0)bo = false;
				h += bian;
			}
			x++;
		}
    }
	return ns;
    }
};

Java代码

class Solution {
    
    
    public String convert(String s, int numRows) {
    
    
		String ns="";
		if(numRows==1||numRows>=s.length())
		{
    
    
		return s;
		}
		for(int i=0;i<numRows;i++)
		{
    
    
			int h=i;//定位
			int d=numRows*2-2;//差值
			int x=0;//区别单双
			int bian=0;
			boolean bo=true;
			while(h<s.length()) {
    
    
				if(bo==true) {
    
    
					ns+=s.charAt(h);
				}
				if(x%2==0) {
    
    
					bian=d-2*i;
					if(bian==0) {
    
    
						bian=numRows*2-2;
					}
					h+=bian;
					bo=true;
				}
				else
				{
    
    
					bian=d-bian;
					if(bian<=0) {
    
    
						bo=false;
						bian=0;
					}
					h+=bian;
				}
				x++;
			}
		}
		return ns;
    }
}

思路
上面的代码的思路都是找规律,因为是一个循环反复的过程,所以通过找规律的方式就不需要多余的空间来存储Z形的字符串了,同时时间上也会快一些。在这里的操作是循环行数次,每次都将每行的字符全部放到对应的目标字符串的正确位置。不同行的字符的变化规律区间的大小不同,同时非首尾行的同一行的字符的规律也有两种,先来说说首尾行。首尾行每次的变化大小为numRows2-2。中间行有两种情况,可以分为奇偶两种,此处说的奇偶是本行的字符的顺序的奇偶,对于奇数的情况可以计算出bian为numRows2-2-2i,i是行号(从0开始),对于偶数的情况是根据奇数的增量来计算的,偶数的bian为numRows2-2-bian,实际上就是因为奇数和偶数的增量加起来等于numRows*2-2从而得出的规律。