将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R E T O E S I I G E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3 输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4 输出: "LDREOEIIECIHNTSG" 解释: L D R E O E I I E C I H N T S G
思路:剖析题目,其实就是扫描字符串,然后依次升序降序写入到不同行中。新建了4个StringBuilder,然后依次将char append到sb中,最后输出结果。
public static String convert(String s, int numRows) {
if(s == null || s.equals("") || numRows == 1)
return s;
List<StringBuilder> res = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
res.add(new StringBuilder());
}
res.get(0).append(s.charAt(0));
int i = 1;
boolean up = true;
int listIndex = -1;
while (i < s.length()){
if(listIndex == -1) {
up = true;
listIndex += 2;
}
if(listIndex == numRows) {
up = false;
listIndex -= 2;
}
if(up)
res.get(listIndex++).append(s.charAt(i));
else
res.get(listIndex--).append(s.charAt(i));
i++;
}
StringBuffer ret = new StringBuffer();
for (int j = 0; j < res.size(); j++) {
ret.append(res.get(j));
}
return ret.toString();
}
Z字形字符串转换
本文介绍了一种将字符串按Z字形排列并重新组合的方法,通过示例详细解析了算法思路,包括如何根据行数调整字符串的排列方式,以及如何通过逐行读取生成新的字符串。
1681

被折叠的 条评论
为什么被折叠?



