LeetCode 6. Z 字形变换
原题链接
中等
作者:
LangB
,
2020-10-27 23:05:10
,
所有人可见
,
阅读 264
class Solution {
public String convert(String s, int n) {
if (n == 1) {
return s;
}
int len = s.length();
StringBuilder res = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i == 0 || i == n - 1) {
for (int j = i; j < len; j += 2 * n - 2) {
res.append(s.charAt(j));
}
} else {
for (int j = i, k = 2 * n - 2 - i; j < len|| k < len; j += 2 * n - 2, k += 2 * n - 2) {
if (j < len) {
res.append(s.charAt(j));
}
if (k < len) {
res.append(s.charAt(k));
}
}
}
}
return res.toString();
}
}