avatar

z字变换(6)
com.wzl.day17;
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

public class Day17 {
//将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
//
// 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
//
// L C I R
//E T O E S I I G
//E D H N
//
//
// 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
//
// 请你实现这个将字符串进行指定行数变换的函数:
//
// string convert(string s, int numRows);
//
// 示例 1:
//
// 输入: s = "LEETCODEISHIRING", numRows = 3
//输出: "LCIRETOESIIGEDHN"
//
//
// 示例 2:
//
// 输入: s = "LEETCODEISHIRING", numRows = 4
//输出: "LDREOEIIECIHNTSG"
//解释:
//
//L D R
//E O E I I
//E C I H N
//T S G
// Related Topics 字符串


//leetcode submit region begin(Prohibit modification and deletion)

public String convert(String s, int numRows) {
char[] c = new char[s.length()];
int size = numRows * 2 - 2; //绝对步长
int index; //记算s下标
int count = 0; //记录c下标
int add; //相对步长
if (numRows < 2) {
return s;
}
for (int i = 0; i < numRows; i++) { //一层一层遍历
index = i;
add = i * 2;
while (index < c.length) { //超出字符串长度计算下一层
c[count] = s.charAt(index);
add = size - add;
index += add == 0 ? size : add;
count++;
}
}
return new String(c);

}

public static void main(String[] args) {
String s = "LEETCODEISHIRING";
Day17 day17 = new Day17();
day17.convert(s,4);
}
}
//leetcode submit region end(Prohibit modification and deletion)
文章作者: 无知的小狼
文章链接: https://bytedance.press/2019/12/23/z%E5%AD%97%E5%8F%98%E6%8D%A2%EF%BC%886%EF%BC%89/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼

评论