본문 바로가기

hacking or software engineering skills/leetcode

6. ZigZag Conversion

반응형

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

 

 

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if not s:
            return s
        if (numRows==1) or (len(s)<numRows):
            return s
        
        zigzeg = {}
        for i in range(len(s)):
            # ex) n = 5
            # row_num       str_idx      cnt    expression
            # 0,1,2,3       0,1,2,3       0     r = s % (n-1)
            # 4,3,2,1       4,5,6,7       1     r = (n+n-2)*(cnt+1)/2-s = (n-1)(cnt+1)-s  
            # 0,1,2,3       8,9,10,11     2     r = s % (n-1)
            # 4,3,2,1       12,13,14,15   3     r = (n+n-2)*(cnt+1)/2-s = (n-1)(cnt+1)-s
            # 0,1,2,3       16,17,18,19   4     r = s % (n-1)
            # 4,3,2,1       20,21,22,23   5     r = (n+n-2)*(cnt+1)/2-s = (n-1)(cnt+1)-s
            col_cnt = i//(numRows-1)
            if col_cnt % 2 == 0:
                r = i % (numRows-1)
                # print(r)
            else:
                r = (numRows-1)*(col_cnt+1)-i
                # print(r)
            if zigzeg.get(str(r)) is None:
                zigzeg[str(r)] = []
            zigzeg[str(r)].append(s[i])
        
        total = []
        for i in range(numRows):
            total += zigzeg.get(str(i)) 
            # print(total)
            # for j in zigzeg[str(i)]:
                # print(j)
            # total.extend(zigzeg[str(i)])
        total = ''.join(total)
        return total

반응형