Z字形变换( ZigZag Conversion)java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangjingao/article/details/82994097

Z字形变换( ZigZag Conversion)java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangjingao/article/details/82994097

题干


将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

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

分析

循环排列。先向下,在斜向上

代码

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        int index = 0;
        char [][] arr = new char[numRows][s.length()];
        int col = 0;
        int row = 0;
        while (index < s.length()) {
            while (row < numRows && index <s.length()) {
                arr[row++][col] = s.charAt(index++);
            }
            row--;
            while (row > 0 && index < s.length()) {
                arr[--row][++col] = s.charAt(index++);
            }
            row++;
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0 ;i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
//                System.out.print(arr[i][j]);
                if (arr[i][j] != '\u0000') {
                    result.append(arr[i][j]);
                }
            }
        
        }
        return result.toString();
    }

运行情况

在这里插入图片描述

我关于算法练习的github代码地址:https://github.com/zhangjingao/algorithm

猜你喜欢

转载自blog.csdn.net/zhangjingao/article/details/82994097