今天继续刷LeetCode,第6题,将字符串用之字型表示。
分析:
通过找规律,发现每次叠加的下标与行数有关。
问题:
1、Python实现;
2、注意下标;
附上C++代码:
class Solution {
public:
string convert(string s, int numRows) {
string ret(s.length(), ' ');
if (numRows > 1)
{
int step = (numRows - 1) * 2;
int counter = 0;
for (int j = 0; j < numRows; j++)
{
for (int i = j; i < s.length(); i = i + step)
{
ret[counter] = s[i];
++counter;
int offset = step - j * 2;
if (offset > 0 && offset < step)
{
int pos = offset + i;
if (pos < s.length())
{
ret[counter] = s[pos];
++counter;
}
}
}
}
} else {
ret = s;
}
return ret;
}
};
附上Python代码:
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
zigzag = ['' for i in range(numRows)] # 初始化zigzag为['','','']
row = 0 # 当前的行数
step = 1 # 步数:控制数据的输入
for c in s:
if row == 0:
step = 1
if row == numRows - 1:
step = -1
zigzag[row] += c
row += step
return ''.join(zigzag)