/**
* Z 字形变换
*
* @author xiaofeifei
* @date 2019-11-06
* @since
*/
public class Solution1 {
/**
* ps:
* numRows = 3 ,s = abc d efg 3 - 2 = 1
*
* a e => s[0] = a s[4] = w => 0 numRows
*
* b d f => s[1] = b s[3] = d s[5] = f
*
* c g => s[2] = c s[6] = g
*
*
* numRow = 4, s= abcd e f ghij 4 - 2 = 2
*
*
* a g => s[0] = a s[6] = g => i = i + numRows + numRows - 2
*
* b f h => s[1] = b s[5] = f s[7] = h => i = i + 2 * numRows - 2
*
* c e i => s[2] = c s[4] = e s[8] = i
*
* d j => s[3] = d s[9] = j
*
* 以下方法以遍历方向的方式将相关字符添加到对应的行
* 0 -> numRows - 1 row++
* numRows - 1 -> 2(numRows - 1) row--
* 2(numRows - 1) -> 3(numRows - 1) row++
*
*
* @param s s的长度大于等于3
* @param numRows
* @return
*/
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
if (s.length() <= numRows) {
return s;
}
// 定义行数组
StringBuilder[] rows = new StringBuilder[numRows];
IntStream.range(0, numRows).forEach( t -> rows[t] = new StringBuilder());
// 定义行索引
int row = 0;
// 行索引是否增加
boolean isIncrease = false;
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
rows[row].append(chars[i]);
if (row == 0) {
isIncrease = true;
} else if (row == numRows - 1) {
isIncrease = false;
}
if (isIncrease) {
row++;
} else {
row--;
}
}
return Stream.of(rows).reduce(StringBuilder::append).get().toString();
}
public static void main(String[] args) {
String str = new Solution1().convert("ab", 1);
System.out.println("str = " + str);
}
}