zoukankan      html  css  js  c++  java
  • 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 text, int nRows);

    convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

    分析:

      这道题主要是找规律。

    方法一:

      比较直观的解法,使用list存储每一行,最后拼接。

    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            res = ['']*numRows
            step = 1
            row = 0
            if len(s) <= 2 or numRows <= 1:
                return s
            for i in range(len(s)):
                res[row] += s[i]
                row += step
                if row >=numRows:
                    row = numRows-2
                    step = -1
                if row < 0:
                    row = 1
                    step = 1
            ans = ''
            for i in range(len(res)):
                ans += res[i]
            return ans

    方法二:

      发现所有行的重复周期都是 2 * nRows - 2,对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 * nRows - 2 - 2 * i

    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            if len(s) < 2 or numRows < 2:
                return s
            jump = 2*(numRows-1)
            res = ''
            for i in range(numRows):
                j = i
                while j < len(s):
                    res += s[j]
                    if i > 0 and i < numRows-1 and j+jump-2*i < len(s):
                        res += s[j+jump-2*i]
                    j += jump
            return res
  • 相关阅读:
    知识付费时代:屌丝程序员如何用技术实现
    过完年了,要不要辞职?
    程序猿不得不知道的业内“黑话”
    Go 2 Draft Designs
    11 Go 1.11 Release Notes
    10 Go 1.10 Release Notes
    09 Go 1.9 Release Notes
    win10系统电脑无法识别u盘的解决办法
    IDEA导入Git项目后右键项目找不到Git选项的解决方法
    Redis在windows下安装与配置
  • 原文地址:https://www.cnblogs.com/Peyton-Li/p/7648549.html
Copyright © 2011-2022 走看看