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);
Examples:
Input: s = “PAYPALISHIRING”, numRows = 3 Output: “PAHNAPLSIIGYIR”
Input: s = “PAYPALISHIRING”, numRows = 4 Output: “PINALSIGYAHRPI” Explanation:
classSolution { public: stringconvert(string s, int numRows){ int len = s.length(); int num = ceil(len*1.0/numRows); string res = ""; int d = 2*numRows-2;
classSolution: defconvert(self, s: str, numRows: int) -> str: slen = len(s) num = math.ceil(slen/numRows); res = "" d = 2*numRows-2 if numRows==1: return s for i in range(numRows): for j in range(1,num+1): if i==0and (j-1)*d<slen: res = res + s[(j-1)*d] elif i==numRows-1and (j-1)*d+numRows-1<slen: res = res + s[(j-1)*d+numRows-1] else : if (j-1)*d+i<slen: res = res + s[(j-1)*d+i] if(j*d-i<slen): res = res + s[j*d-i] return res;