6. ZigZag Conversion

Source: Internet
Author: User

The string "Paypalishiring" is written with a zigzag pattern on a given number of rows like this: (You could want to display T His 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: "Pahnaplsiigyir"

Write the code that would 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, numRows):        """        :type s: str        :type numRows: int        :rtype: str        """        l = [‘‘ for _ in range(numRows)]        if numRows == 1:            return s        total = 2*(numRows-1)        for i in range(len(s)):            pos = i % total            if pos > numRows-1:                pos = total - pos            l[pos] += s[i]        res = ‘‘        for i in range(numRows):            res += l[i]        return res

There is no need to initialize the entire matrix, just initialize a one-dimensional list,l[i] to save the case of line I.

6. ZigZag Conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.