题目
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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
思路
1. 由于每一行到底有多少个字母是不确定的,因此每行使用ArrayList来保存字母
2. 遍历字符串:分为三个部分:第一部分循环,即从上往下走;第二部分条件判断,判断从上往下走是否已经到达最下层,若到达,下一步应该往上走,因此ArrayList的标号应该减2;第三部分循环,是从下往上走;
3. 遍历结束时,list[0]中保存的是第一行的字符串,list[1] 中保存的是第二行字符串,以此类推......
Java代码
// Runtime: 11 ms, faster than 65.73%
// Memory Usage: 39.4 MB, less than 76.08%
class Solution {
public String convert(String s, int numRows) {
if(s == null || s.length() < 1 || numRows <= 1)
return s;
List<List> list = new ArrayList<List>();
for(int i = 0; i < numRows; i++)
list.add(new ArrayList<Character>());
int index = 0; // 当前行数
int n = 0; // 当前字母的下标
int len = s.length();
while(n < len){
while(index < numRows && n < len){
list.get(index).add(s.charAt(n));
index++;
n++;
}
if(index == numRows)
index -= 2;
while(index > 0 && n < len){
list.get(index).add(s.charAt(n));
index--;
n++;
}
}
StringBuffer str = new StringBuffer();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).size(); j++){
str.append(list.get(i).get(j));
}
}
return str.toString();
}
}