class Solution {
public String convert(String s, int numRows) {
int rows = Math.min(s.length(), numRows);
if(rows == 1) return s;
int rowIndex = 0;
StringBuilder result = new StringBuilder();
List<StringBuilder> list = new ArrayList<>();
for(int i = 0; i < rows; i++) list.add(new StringBuilder());
for(int i = 0; i < s.length(); i++){
int judge = i / (rows - 1);
int index = 0;
if(judge % 2 == 0) index = i % (rows - 1);
else index = rows - 1 - i % (rows - 1);
list.get(index).append(s.charAt(i));
}
for(StringBuilder rowStr: list) result.append(rowStr);
return result.toString();
}
}
这个解法还需要事先对列表赋值,最好能够直接找出结果字符串的指定位置的字符并放进去
class Solution {
public String convert(String s, int numRows) {
int rows = Math.min(s.length(), numRows);
if(rows == 1) return s;
StringBuilder result = new StringBuilder();
for(int i = 0; i < rows; i++){
int d1 = (rows - 1 - i) * 2;
int d2 = i * 2;
int d = 1;
int current = i;
while(current < s.length()){
if(d != 0)
result.append(s.charAt(current));
d = (d == d1) ? d2 : d1;
current += d;
}
}
return result.toString();
}
}