Version #2
直接for循环,明显比自己写的好
55.05 %
class Solution {
public String convert(String s, int numRows) {
if (s == null || s.length() == 0) return s;
int index = 0;
int length = s.length();
List<StringBuilder> sbList = new ArrayList<>();
for (int i = 0; i < numRows; i++) sbList.add(new StringBuilder());
while (index < length) {
for (int i = 0; i < numRows && index < length; i++) {
sbList.get(i).append(s.charAt(index++));
}
for (int j = numRows - 2; j >= 1 && index < length; j--) {
sbList.get(j).append(s.charAt(index++));
}
}
StringBuilder result = new StringBuilder();
for (StringBuilder sb : sbList) result.append(sb);
return result.toString();
}
}
Version #1
自己写的方法
发现zigzag实际上是 01234321012343210这种顺序
所以写一个rowCounter和一个表示是不是reverse的boolean
如果只有一行的情况下会有出界的exception所以numRows == 1的时候要特殊处理
55.05 %
class Solution {
public String convert(String s, int numRows) {
if (s == null || s.length() == 0 || numRows <= 1) return s;
List<StringBuilder> list = new ArrayList<>();
for (int i = 0; i < numRows; i++) list.add(new StringBuilder());
int index = 0;
int row = 0;
boolean reverse = false;
while (index < s.length()) {
list.get(row).append(s.charAt(index));
if ((row == 0 && reverse) || (row == numRows - 1 && !reverse)) {
reverse = !reverse;
}
if (reverse) row--;
else row++;
index++;
}
StringBuilder result = new StringBuilder();
for (StringBuilder sb : list) {
result.append(sb);
}
return result.toString();
}
}
No comments:
Post a Comment