题目描述:将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
e.g:
-
输入: s = "LEETCODEISHIRING", numRows = 3 输出: "LCIRETOESIIGEDHN"
-
输入: s = "LEETCODEISHIRING", numRows = 4 输出: "LDREOEIIECIHNTSG"
思路:
java代码
/**
* 题目4: 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
* e.g: 1. 输入: s = "LEETCODEISHIRING", numRows = 3 输出: "LCIRETOESIIGEDHN"
* 2. 输入: s = "LEETCODEISHIRING", numRows = 4 输出: "LDREOEIIECIHNTSG"
* @param s
* @return
*/
private static String solution05(String s, int numRows) {
if (1 == numRows) {
return s;
}
char[] input = s.toCharArray();
int length = input.length;
StringBuilder result = new StringBuilder();
for (int i = 0; i < numRows && i < length; i++) {
// 第一列
result.append(input[i]);
for (int j = i + 2 * (numRows - 1); j < length || (j - 2 * i) < length; j = j + 2 * (numRows - 1)) {
// 非首行和末行
if (0 != i && (numRows - 1) != i) {
result.append(input[j - 2 * i]);
}
if (j < length) {
result.append(input[j]);
}
}
}
return result.toString();
}
算法时间复杂度:结果长度为n,共会有n次append操作,所以复杂度为O(n)。
网友评论