zoukankan      html  css  js  c++  java
  • Z 字形变换

    将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

    比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

    L   C   I   R
    E T O E S I I G
    E   D   H   N
    

    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"

    请你实现这个将字符串进行指定行数变换的函数:

    string convert(string s, int numRows);

    示例 1:

    输入: s = "LEETCODEISHIRING", numRows = 3
    输出: "LCIRETOESIIGEDHN"

    示例 2:

    输入: s = "LEETCODEISHIRING", numRows = 4
    输出: "LDREOEIIECIHNTSG"
    解释:
    
    L     D     R
    E   O E   I I
    E C   I H   N
    T     S     G

    思路

    按照与逐行读取 Z 字形图案相同的顺序访问字符串。

    算法

    首先访问 行 0 中的所有字符,接着访问 行 1,然后 行 2,依此类推...

    解法一:

    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            if numRows <= 1:
                return s
            n = len(s)
            ans = []
            step = 2 * numRows - 2
            for i in range(numRows):
                one = i
                two = -i
                while one < n or two < n:
                    if 0 <= two < n and one != two and i != numRows - 1:
                        ans.append(s[two])
                    if one < n:
                        ans.append(s[one])
                    one += step
                    two += step
            return "".join(ans)

    解法二:

    class Solution:
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            # no need to convert
            if numRows == 1:
                return(s)
    
            zlist = []
            sc = ""
            n = numRows
    
            # create null list
            while n:
                zlist.append([])
                n = n - 1
    
            j = 0
            for a in s:
                if j == 0:
                    # direction change
                    coverse = False
                zlist[j].append(a)
                if j + 1 < numRows:
                    if coverse:
                        j = j - 1
                    else:
                        j = j + 1
                else:
                    j = j - 1
                    # direction change
                    coverse = True
    
            # get the converted string
            for z in zlist:
                for t in z:
                    sc = sc + t
            return(sc)
  • 相关阅读:
    ingress高可用--使用DaemonSet方式部署ingress-nginx
    flask-Migrate模块
    flask 框架 前端和后端请求超时问题
    linux crontab执行python脚本问题
    python 装饰器
    Python 中实现装饰器时使用 @functools.wraps 的理由
    jquery ui dialog 中使用select2 导致select2的input失去焦点的解决方法
    Django之ModelForm组件
    Django之Model操作
    Java环境变量,真的还有必要配吗?
  • 原文地址:https://www.cnblogs.com/Estate-47/p/10638667.html
Copyright © 2011-2022 走看看