-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6.z-字形变换.java
61 lines (54 loc) · 1.42 KB
/
6.z-字形变换.java
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
/*
* @lc app=leetcode.cn id=6 lang=java
*
* [6] Z 字形变换
*/
// @lc code=start
/*
//推导公式方法
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1){
return s;
}
StringBuilder ret = new StringBuilder();
int index = 2 * numRows - 2;
int n = s.length();
for(int i = 0;i < numRows; i++){
for(int j = 0; j + i < n; j += index){
ret.append(s.charAt(j + i));
if(i != 0 && i != numRows - 1 && j + index - i < n){
ret.append(s.charAt(j + index - i));
}
}
}
return ret.toString();
}
}*/
//列表模拟排列方法
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1){
return s;
}
List<StringBuilder> l = new ArrayList<>();
for(int i=0;i<Math.min(s.length(),numRows);i++){
l.add(new StringBuilder());
}
int cur = 0;
boolean flag = false;
for(char c : s.toCharArray()){
l.get(cur).append(c);
if(cur == 0 || cur == numRows - 1){
flag = !flag;
}
cur += flag ? 1 : -1;
}
StringBuilder ans = new StringBuilder();
for(StringBuilder sb : l){
ans.append(sb);
}
return ans.toString();
}
}
// @lc code=end