The string "PAYPALISHIRING"
is written in
a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.题目来自: https://oj.leetcode.com/problems/zigzag-conversion/
这一题的难度标注为"Easy",不过我觉得这题目非常有趣。
题目要求是把一个字符串按照它的"Z"形式的顺序输出。所谓"Z"形式就是竖直排列,斜向上换行。
比如 HelloWorld 的三层Z形式是这样:
H o l
e l W r d
l o
要求输出的是HolelWrdlo.
解决的思路就是逐行计算如果有可以填充(只要没有超出原始长度)的字符,它在原始的字符串中应该是什么位置(sindex, sindex),取到该字符并填充到目标list中。
需要注意的是Z形状的规律,我是把一个竖直加一个斜方向上升作为一个单元。
class Solution:
# @return a string
def convert(self, s, nRows):
lists = []
lens = len(s)
grp = (2 * nRows - 2) if nRows >= 3 else nRows
for iR in range(nRows):
sindex = iR
while sindex < lens:
lists.append(s[sindex])
if iR > 0 and iR < (nRows - 1):
sindex2 = (sindex + grp - 2 * iR)
if sindex2 < lens:
lists.append(s[sindex2])
sindex += grp
return ''.join(lists)
python讨厌的一点是字符串是不可写的,只能先用字符list,最后再把list通过join的形式构造出字符串来。这题用c语言写可能更简洁。
''.join(lists)