Solution by python3


  • 0
    Y

    Simple and easy to understand!

    class Solution:
        # this method runtime beats 68.55% of python 3 submissions
        def convert(self, s, numRows):
            i = 0
            s_len = len(s)
            new_s = ''
            zigzag = dict()
            for j in range(numRows):
                zigzag[j] = []
            while i < s_len:
                # add from the first line to the end
                for j in range(numRows):
                    if i < s_len:
                        zigzag[j].append(s[i])
                        i += 1
                # add backwards from penultimate one to the second
                for j in range(numRows)[numRows-2:0:-1]:
                    if i < s_len:
                        zigzag[j].append(s[i])
                        i += 1
    
            # add together to form a new string
            for m in range(numRows):
                for n in zigzag[m]:
                    new_s += n
    
            return new_s
    
    if __name__ == '__main__':
        s = "PAYPALISHIRING"
        solution = Solution()
        new_s = solution.convert(s,3)
        print(new_s)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.