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
刚看题的表情

这特么什么鬼(ps: 注意文明用语)不要慌,内事问百度,外事谷歌,先百度一下吧,首先和我一样的英语渣们,福利在下面

题目大概意思就是,按照Z字形或者说锯齿型变换字符串,那是什么意思呢?看下图


根据上题的例子,我们将一个字符串"PAYPALISHIRING"根据图形表示的方式排列,然后按我们习惯的从左到右从上到下的顺序,将字符拼接起来,连成一个字符串"PAHNAPLSIIGYIR"。

下面开始找规律,其实还是挺简单的,看见这种图形,只需要根据列数定义三个变量依次接收对应行的字符,最后再拼接成一个字符就完事了,说了这么多,看下代码就很简单了

public static void main(String[] args){
        System.out.print(convert("PAYPALISHIRING", 3));
    }
    public static String convert(String s, int numRows) {
        if (s.length() < 2 || numRows < 2) return s;

        StringBuilder[] sbs = new StringBuilder[numRows];
        int sbsIndex = 0;
        int direction = 1;
        for (int i = 0; i < s.toCharArray().length; i++) {
            if (sbs[sbsIndex] == null){
                sbs[sbsIndex] = new StringBuilder();
            }
            sbs[sbsIndex].append(s.charAt(i));
            sbsIndex += direction;
            direction = sbsIndex == numRows-1 ? -1 : sbsIndex == 0 ? 1 : direction;
        }
        StringBuilder result = new StringBuilder();
        for (StringBuilder sb : sbs) {
            result.append(sb == null ? "" : sb);
        }
        return result.toString();
    }

根据代码,我们将每一行认为是一个数组,那么题目意思,无非就是往复的用每一个数组来接收给定字符串的元素了。

比如,根据题意,定义三个数组 array1 array2 array3


看图 array1 [0] = "P" array2[0] = "A" array3[0] = “Y” array2[1] = “P” array1[1] = “A” 以次类推直到循环完整个字符串。 

老规矩,点击查看更多解题思路

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值