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
Example 3:
Input: s = "A", numRows = 1 Output: "A"
Constraints:
1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case),','
and'.'
.1 <= numRows <= 1000
import numpy as np
class Solution(object):
def convert(self, s, numRows):
numCols = len(s)
arr_characters = np.zeros(numRows * numCols).reshape(numRows, numCols)
#print(arr_characters)
if numRows == 1:
return s
else:
counter = 0
pos = 0
vertical_shift = 0
for i in range(len(s)):
if counter <= numRows:
_zero = 0
for j in range(numRows):
if pos >= len(s):
break
else:
#print(s[pos],end=' ')
#print("(",_zero,vertical_shift,")",end= ' ') # = ord(s[pos])
arr_characters[_zero][vertical_shift] = ord(s[pos])
pos += 1
_zero += 1
counter = numRows + 1
vertical_shift += (numRows - 1)
#print(vertical_shift,"***************")
else:
diagonal_shift_col = vertical_shift - (numRows - 2)
diagonal_shift_row = numRows - 2
for j in range(numRows - 2):
if pos >= len(s):
break
else:
#print(s[pos],end = ' ')
#print("(",diagonal_shift_row,diagonal_shift_col,")",end= ' ') # = ord(s[pos])
arr_characters[diagonal_shift_row][diagonal_shift_col] = ord(s[pos])
diagonal_shift_col += 1
diagonal_shift_row -= 1
pos += 1
#print("**************")
counter = 0
#print(arr_characters)
output = ""
for i in range(numRows):
for j in range(numCols):
if arr_characters[i][j] != 0:
output += chr(int(arr_characters[i][j]))
else:
output += ""
#output.encode('utf-8')
return output
obj = Solution()
s = ""
numRows = int(input("Enter the number of rows:"))
s = str(input("Enter the string:"))
print(obj.convert(s, numRows))
No comments:
Post a Comment