友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

6. 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)

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

思路分析

  • 一刷

  • 二刷

 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * Runtime: 5 ms, faster than 73.81% of Java online submissions for ZigZag Conversion.
 *
 * Memory Usage: 38.7 MB, less than 77.68% of Java online submissions for ZigZag Conversion.
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2019-07-14 18:20
 */
public String convert(String s, int numRows) {
    if (Objects.isNull(s) || s.length() == 0) {
        return "";
    }
    if (numRows == 1) {
        return s;
    }
    int length = s.length();
    int columnLength = length / numRows;

    StringBuilder[] builders = new StringBuilder[numRows];
    for (int i = 0; i < builders.length; i++) {
        builders[i] = new StringBuilder(columnLength);
    }

    int direction = 1;
    int selector = 0;
    char[] chars = s.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (selector == 0) {
            direction = 1;
        }
        if (selector == numRows - 1) {
            direction = -1;
        }
        char aChar = chars[i];
        builders[selector].append(aChar);
        selector += direction;
    }

    StringBuilder result = new StringBuilder(length);
    for (StringBuilder builder : builders) {
        result.append(builder);
    }
    return result.toString();
}
 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
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-18 20:27:18
 */
public String convert(String s, int numRows) {
  if (numRows < 2) {
    return s;
  }
  List<StringBuilder> sbs = new ArrayList<>(numRows);
  for (int i = 0; i < numRows; i++) {
    sbs.add(new StringBuilder());
  }
  int i = 0, flag = -1;
  for (char c : s.toCharArray()) {
    sbs.get(i).append(c);
    if (i == 0 || i == numRows - 1) {
      flag = -flag;
    }
    i += flag;
  }
  StringBuilder result = new StringBuilder();
  for (StringBuilder sb : sbs) {
    result.append(sb);
  }
  return result.toString();
}