0
点赞
收藏
分享

微信扫一扫

【LeetCode全题库算法速练】6、N 字形变换

TiaNa_na 2023-07-24 阅读 67

(文章目录)

🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈   🍂个人博客首页: KJ.JK   💖系列专栏:LeetCode全题库算法速练

一、题目

🔸题目描述

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。   比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

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" 解释: 在这里插入图片描述

🔸样例3

输入:s = "A", numRows = 1 输出:"A"

二、代码参考


class Solution {
    static int N = 1010;
    static char[][] g = new char[N][N];
    static int[] idxs = new int[N];
    public String convert(String s, int m) {
        if (m == 1) return s;
        int n = s.length();
        Arrays.fill(idxs, 0);
        for (int i = 0, j = 0, k = 1; i < n; i++) {
            g[j][idxs[j]++] = s.charAt(i);
            j += k;
            if (j < 0) {
                j += 2; k = 1;
            } else if (j == m) {
                j -= 2; k = -1;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < idxs[i]; j++) {
                sb.append(g[i][j]);
            }
        }
        return sb.toString();
    }
}

作者:KJ.JK

举报

相关推荐

0 条评论