【数组】【leetCode高频】:6. Z 字形变换

1、题目描述

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

2、算法分析

1 1 1

1 1 1 1 1

1 1 1

这样看,Z往左旋转90度就是题目中说的Z字形。

字符串s按照题目中给的numRows每行打印,然后返回结果。

思路:

①字符串s从0到numRows - 1,然后在从numRows - 1到0折返。

每一列对应的行数据,可以保存在一个List集合中。

②最后只要把每一行的数据拼接就可以。

①res[i] += c: 把每个字符 c 填入对应行 s
②i += flag: 更新当前字符 c 对应的行索引;
③flag = - flag: 在达到 ZZ 字形转折点时,执行反向。

3、代码实现

复制代码
/**
    字符串s是从上当下,从左到右的。
    记录每一行的情况,
 */
class Solution {
    public String convert(String s, int numRows) {
        // 如果行数小于2,返回s
        if(numRows < 2){
            return s;
        }
        // 使用StringBuilder做拼接
        List<StringBuilder> rows = new ArrayList<>();
        //每一行添加进List中
        for(int i = 0;i < numRows;i++){
            rows.add(new StringBuilder());
        }
        // 定义List下标和,反转的标记
        int i = 0;
        int flag = -1;
        // 遍历s
        for(char c : s.toCharArray()){
            // 每行拼接
            rows.get(i).append(c);
            // 当遍历到第一行和numsRows - 1的时候,折返
            if(i == 0 || i == numRows - 1){
                flag = -flag;
            }
            // 更改下标
            i += flag;
        }
        // 拼接
        String res = "";
        for(StringBuilder str:rows){
            res += str;
        }
        return res;
    }
}
复制代码

 

posted on 2022-05-03 21:39  晓风残月一望关河萧索  阅读(59)  评论(0)    收藏  举报

导航

< 2025年6月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 1 2 3 4 5
6 7 8 9 10 11 12
点击右上角即可分享
微信分享提示