LeetCode.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 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

思路:一看就知道是找规律的题,小学的时候最讨厌这种类型的题目了,老老实实的推算吧

在这里插入图片描述

很容易的发现了规律,把图上的Z字型分为两种数据,第一种是竖排,第二种是斜排(黄色标记)

竖排数字之间的相差的值是一定的,与numRows值相结合,发现,相差值是2*numRows-2

每个黄色数字也是有规律的
黄色数字是 它的下一个竖排数字减去 2倍的黄色数字所在的行数,即k-2*i(k是下一个竖排数字,i是该黄色数字所在的行数)。

或者也可以这么理解黄色数字是 上一个竖排数字,加上2*numRows-2之后,再减去2倍的黄色数字所在的行数,即j+2 * numRows-2-2*i

代码如下:

package com.Ryan;

public class ZigZagConversion {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String string = "PAYPALISHIRING";
		int numRows = 3;
		System.out.println(convert(string, numRows));
	}

	static String convert(String s, int numRows) {
		if (numRows <= 1) {
			return s;
		}
		String reString = "";
		int size1 = 2 * numRows - 2;
		for (int i = 0; i < numRows; i++) {
			for (int j = i; j < s.length(); j += size1) {
				reString += s.charAt(j);
				int size2 = j + size1 - 2 * i;
				if (i != 0 && i != numRows - 1 && size2 < s.length()) {
					reString += s.charAt(size2);
				}
			}
		}
		return reString;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_32350719/article/details/88902189