LeetCode 6. Zigzag Conversion

Zigzag Conversion Medium

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)

完整介绍 https://leetcode.com/problems/zigzag-conversion/

题目是要把文字依 Z 的形状排列后,再重新组起来
其实把文字在纸上写一下,就会找出规则,并不太难,列为 Medium,其实有点偏 Easy
重点大概就是找出规则,如图,

http://img2.58codes.com/2024/20105641Az1KVXCNIV.jpg

1 -> 7 需要经历 6 步,同样 7 -> 13 也是 6 步,最后一列也是一样的规则
第二列 2 -> 6 需要 4 步,6 -> 8 需要 2 步,然后又是 4 步,2 步,4 步,2 步的变化
第三列 3 -> 5 需要 2 步,5 -> 9 需要 4 步,然后又是 2 步,4 步,2 步,4 步的变化

找到这个规则后就可以写出程式了。

public class A0006_ZigzagConversion {    public String convert(String input, int numRows) {if (numRows <= 1)return input;StringBuilder output = new StringBuilder();int step = (numRows - 1) * 2;for (int row=0; row<numRows; row++) {int step1 = step - row * 2; // if step is 8, row is 1, step1 6 step2 2int step2 = step - step1;int[] steps = new int[] {step1, step2};if (row == 0 || row == numRows-1)steps = new int[] {step, step};int idx = row;int stepIdx = 0;while (idx < input.length()) {output.append(input.charAt(idx));idx += steps[stepIdx%2];stepIdx++;}}        return output.toString();    }}

这版先用 StringBuilder 较好懂,用 char[] 来存的话会更快一些,但其实也没快到哪


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章