package com.jt.controller.user.algorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ZCharacterTransformation {
public static void main(String[] args) {
String s = "PAYPALISHIRING";
Integer numRows = 3;
String convert = convert(s, numRows);
// 输出:PAHNAPLSIIGYIR
System.out.println(convert);
}
public static String convert(String s, int numRows) {
int length = s.length();
// 判断条件,字符串的长度小于等于行数时,行数小于1时,直接返回字符串
if(s == null || "".equals(s) || length <= numRows || numRows <= 1){
return s;
}
String a= "";
// 声明一个集合,集合中装的字符串对象,一个字符串是一行数据
List<String> rows = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
rows.add("");
}
// 行号
int arow = 0;
// 判断加一行还是减一行
Boolean flag = false;
for (char c : s.toCharArray()) {
// 将当前的字符放入对应的行的字符串
String s1 = rows.get(arow);
s1= s1+c;
// 更新字符串
rows.set(arow,s1);
/** 行数是从0开始的 所以最后一行需要减1
* arow == 0 当在第一行时:需要添加行号
* arow == numRows -1 当在最后一行时,就需要减行来添加数据
*/
if(arow == 0 || arow == numRows -1){
// 更换boolean值
flag = !flag;
}
// 加减行
arow += flag ? 1:-1;
}
// 将所有的字符串进行拼接
a = rows.stream().collect(Collectors.joining(""));
return a;
}
}
思想: 主要是将字符串的字符一个一个的进行添加,所以每添加一个字符要更换行号来添加下一个字符。行号就是上下进行移动添加。