ZigZag Conversion(Z字变形)

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

题解

 这道题就是看坐标的变化。并且需要分块处理。

 n=2时,字符串坐标变成zigzag的走法就是:

 0 2 4 6

 1 3 5 7

 n=3时的走法是:

 0     4     8

 1  3 5  7 9

 2     6    10 

 n=4时的走法是: 

 0      6        12

 1   5 7    11 13

 2 4   8 10    14

 3      9         15 

可以发现规律,画红色的长度永远是 2n-2

用二维数组存放Z字变换之后的字符,只需找出字符串对应字符下标与其在二维数组中位置的规律即可。

代码:

    //ZZC -- Z字形变换
    public static String getZZC(String s , int numRows){
        
        if(numRows == 1){
            return s;
        }
        
        char[] c = s.toCharArray();
        //将一连串的Z按照的上中部重新划分
        int zNum = 2*numRows-2;
        int len = c.length;
        int ySize = (len/zNum+1)*(numRows-1);
        
        char[][] zzc = new char[numRows][ySize];
        
        for (int i = 0; i < len; i++) {
            int ax = i%zNum , ay = (i/zNum)*(numRows-1);
            int bx = numRows - (i%zNum-numRows+1)-1 , by = (i/zNum)*(numRows-1)+(i%zNum)-numRows+1;
            
            if(i%zNum<numRows){
                zzc[ax][ay] = c[i];
            }
            
            if(i%zNum>=numRows){
                zzc[bx][by] = c[i];
            }
        }
        
        String res = "";
        
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < ySize; j++) {
                System.out.print(zzc[i][j]+" ");
                if(zzc[i][j]!='\u0000'){
                    res += zzc[i][j];
                }
            }
            System.out.println("");
        }
        System.out.println(res);
        return res;
    }

 

转载于:https://www.cnblogs.com/wkcode/p/10384843.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值