6.Z字形变换
题目描述
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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
C++
- 把画Z字形分成两个步骤
- 从上到下,竖着画
- 从下到上,往右上方画
- 画的时候,没必要那么死板,因为最后逐行读取的时候是没有计入空格的,所以可以不用纠结空格,
class Solution {
public:
string convert(string s, int numRows) {
string t[numRows];
int len = s.length(), i = 0;
//不需要那么死板,非得排成Z字形,因为最后都是要按行读取输出的,没有输出空格
while(i<len){
//往下
for(int j = 0;j<numRows && i<len;j++){
t[j] +=s[i++];
}
//往上,注意要去除头尾
for(int j = numRows-2;j>0 && i<len;j--){
t[j] +=s[i++];
}
}
//实现按行读取
string ans;
for(int j=0;j<numRows;j++)
ans += t[j];
return ans;
}
};
Python
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
t = [""] * numRows
n = len(s)
i = 0
while i<n:
for j in range(numRows):
if i<n:
t[j] += s[i]
i += 1
for j in range(numRows-2,0,-1):
if i<n:
t[j] += s[i]
i += 1
ans = ""
for ss in t:
ans += ss
return ans