LeetCode-6.ZigZag Conversion(Medium):
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 R
And 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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
我的解法:
这段程序应该也是当时在网上找的参考,首先将字符串分组,按照z字形的规律,比如:
P I N A L S I G Y A H R P I
就被分成 PAYPAL ISHIRI NG每组字符数量是numRows*2-2,然后通过统计规律进行读取就可以了。这道题就难在规律需要我们通过大量举例分析找出来。
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows:
:rtype: str
"""
if s == "":
return ""
if numRows == 1:
return s
ans = ""
mid = []
groupnumber = (len(s)//(numRows*2-2)) if len(s)%(numRows*2-2)==0 else (len(s)//(numRows*2-2)+1)
for i in range(0,groupnumber):
if (i+1)*(numRows*2-2) <= len(s):
mid.append(s[i*(numRows*2-2):(i+1)*(numRows*2-2)])
else:
mid.append(s[i*(numRows*2-2):])
#print(mid)
for j in range(0,groupnumber):
ans += mid[j][0]
#print(ans)
if numRows!=2:
for k in range(1,numRows-1):
for l in range(0,groupnumber):
if k<len(mid[l]):
ans += mid[l][k]
if numRows*2-2-k<len(mid[l]):
ans += mid[l][numRows*2-2-k]
for j in range(0,groupnumber):
if numRows-1<len(mid[j]):
ans += mid[j][numRows-1]
return ans