力扣刷题6.Z 字形变换

英文题目

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)
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:

L   C   I   R
E T O E S I I G
E   D   H   N

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

思路

将每行打印的,按行排序
通过从左向右迭代字符串,我们可以轻松地确定字符位于 Z 字形图案中的哪一行。

  1. 按每行进行排序 len 为几 则为几个数组
  2. 向下 向左 移动 标志位 down true 向下 false 向左时 往上移动一格
  3. 移动时判断是否定格需要变换方向
P     I    N
A   L S  I G
Y A   H R
P     I
-->
P I N
A L S I G
Y A H R
P I

代码

class Solution {
    public String convert(String s, int numRows) {
        
         if (numRows == 1) return s;
        
        int row = Math.min(s.length(),numRows);
        List stringBuffers = new ArrayList<>();
         for (int i = 0; i < row; i++)
            stringBuffers.add(new StringBuilder());
        //初始化  i== 0 帮我们转过来
        boolean down = false;
        int currentRow = 0;
        
        
        for (char c : s.toCharArray()) {
            stringBuffers.get(currentRow).append(c);
            if (currentRow == 0 || currentRow == numRows - 1) down = !down;
            currentRow += down ? 1 : -1;
        }

        
        
        StringBuilder ret = new StringBuilder();
        for (StringBuilder stringBuffer : stringBuffers) ret.append(stringBuffer);
        return ret.toString();
    }
}

你可能感兴趣的:(力扣腾讯精选50道)