LeetCode 6. 【Java】6. ZigZag Conversion
原题链接
中等
作者:
tt2767
,
2020-02-12 14:51:00
,
所有人可见
,
阅读 834
/*
1. 暴力解法: 都投影到y轴,用指针判断投影顺序并输出,是否奇形怪状的题大部分都用这种方法?
2. 找规律:因为是循环的,所以可以找规律,
等差数列: https://www.acwing.com/solution/LeetCode/content/75/
*/
class Solution {
public String convert(String s, int numRows) {
if (s == null || s.length() == 0 || s.length() == 1 || numRows == 0 || numRows == 1) return s;
var res = arithSeq(s, numRows);
return res;
}
public String bruteForce(String s, int n){
List<StringBuilder> list = new ArrayList<>();
for (int i = 0 ; i < n ; i++) list.add(new StringBuilder());
int next = -1;
int index = 0;
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
list.get(index).append(c);
if (index % n == 0 || index % n == n-1) next = -next;
// 会导致index 读到 n, 因为在第一个循环节后 i==n 时 index == n-2 , 如果用i%n则 i%n == 0 导致再次转下向
// 故更新判断应该用最近的一个变量
// if (i % n == 0 || i % n == n-1) next = -next;
index += next;
}
var buffer = list.get(0);
for (int i = 1 ; i < n ;i ++){
buffer.append(list.get(i).toString());
}
return buffer.toString();
}
public String arithSeq(String s, int n){
StringBuilder buffer = new StringBuilder();
int step = 2*n-2;
for (int i = 0 ; i < n ;i ++){
for (int k = i, j = step - i; k < s.length() || j < s.length() ; k += step, j+= step){
if (k < s.length()) buffer.append(s.charAt(k));
if (i == 0 || i == n-1) continue;
if (j < s.length()) buffer.append(s.charAt(j));
}
}
return buffer.toString();
}
}