leetcode 6:Z字形变换
将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = "PAYPALISHIRING", numRows = 3 输出:"PAHNAPLSIIGYIR"
示例 2:
输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I
示例 3:
输入:s = "A", numRows = 1 输出:"A"
提示:
-
1 <= s.length <= 1000
-
s
由英文字母(小写和大写)、','
和'.'
组成 -
1 <= numRows <= 1000
Related Topics
字符串
思路1 :
Z字形变换经过发现,有2种形式:
-
第一种,生成完整地列,行号变化范围是[0,numRows-1]。
-
第二种,中间的列,每列只有一个元素,行号变化范围是[numRows -2 , 1];
public String convert(String s, int numRows) { ArrayList<ArrayList<Character>> result = new ArrayList<>(); for(int i = 0 ; i < numRows;i++){ ArrayList<Character> list = new ArrayList<>(); result.add(list); } int index = 0; // 遍历s的下标 while(index < s.length()){ //先添加完整的列 for(int i = 0 ; i < numRows && index < s.length();i++){ //i是行号 result.get(i).add(s.charAt(index)); index++; } //添加 Z字形中间的列 // Z中间只有一个字母的列 行数变化范围 [1 numRows - 2] for(int i = numRows -2 ; i > 0 && index < s.length();i--){ //i表示的是行号的变化 result.get(i).add(s.charAt(index)); index++; } } StringBuilder sb = new StringBuilder(); for(int i = 0; i < result.size();i++){ for(int j = 0 ; j < result.get(i).size();j++){ sb.append(result.get(i).get(j)); } } return sb.toString(); 执行耗时:6 ms,击败了46.64% 的Java用户 内存消耗:42.1 MB,击败了5.75% 的Java用户
思路1 改进:通过把每一行统计的arraylist换成stringbuilder,性能有了小幅度提升。
public String convert(String s, int numRows) { ArrayList<StringBuilder> result = new ArrayList<>(); for(int i = 0 ; i < numRows;i++){ result.add(new StringBuilder()); } int index = 0; // 遍历s的下标 while(index < s.length()){ //先添加完整的列 for(int i = 0 ; i < numRows && index < s.length();i++){ //i是行号 result.get(i).append(s.charAt(index)); index++; } //添加 Z字形中间的列 // Z中间只有一个字母的列 行数变化范围 [1 numRows - 2] for(int i = numRows -2 ; i > 0 && index < s.length();i--){ //i表示的是行号的变化 result.get(i).append(s.charAt(index)); index++; } } StringBuilder sb = new StringBuilder(); for(int i = 0 ; i < result.size();i++){ sb.append(result.get(i)); } return sb.toString(); }