zoukankan      html  css  js  c++  java
  • Leetcode题库——6.Z字形变换


    @author: ZZQ
    @software: PyCharm
    @file: convert.py
    @time: 2018/9/20 20:12
    要求: Z字形变换
    将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
    P A H N
    A P L S I I G
    Y I R
    之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
    实现一个将字符串进行指定行数变换的函数:

    string convert(string s, int numRows);
    e.g.:
            输入: s = "PAYPALISHIRING", numRows = 3
            输出: "PAHNAPLSIIGYIR"
            输入:s = "PAYPALISHIRING", numRows = 4
            输出:"PINALSIGYAHRPI"
    

    思路: 建一个有numRows个字符串的列表,一个循环写两次列表,一次顺着写,一次反着写,注意下标变化。

    class Solution():
        def __init__(self):
            pass
    
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            if numRows == 1:
                return s
            s_len = len(s)
            zlist = []
            for i in range(numRows):
                sub_list = ""
                zlist.append(sub_list)
            k = 0
            time = 0
            while k < s_len:
                if time == 0:
                    list_index = 0
                    while list_index < numRows:
                        if k < s_len:
                            zlist[list_index] += s[k]
                        else:
                            break
                        k += 1
                        list_index += 1
                    time += 1
                else:
                    list_index = 1
                    while list_index < numRows:
                        if k < s_len:
                            zlist[list_index] += s[k]
                        else:
                            break
                        k += 1
                        list_index += 1
    
                list_index -= 1
                while list_index > 0:
                    list_index -= 1
                    if k < s_len:
                        zlist[list_index] += s[k]
                    else:
                        break
                    k += 1
                time += 1
            z_str = ""
            for sub_str in zlist:
                z_str += sub_str
            return z_str
    
    
    if __name__ == "__main__":
        answer = Solution()
        print answer.convert(s="ABJHFSDKAGFSLABVSJDK", numRows=2)
    
    CV小蜡肉
  • 相关阅读:
    python D32 管道、线程池
    python D31 守护进程、进程锁、队列
    python D30 进程
    python 30 进程之间的相互独立、进程之间的时间差
    python D30 操作系统历史
    python D29 socketserver以及FTB
    python D28 粘包
    net4.0 task 超时任务代码 用Thread.sleep方式实现
    sql取随机结果集
    【ecshop---新增包邮卡功能】
  • 原文地址:https://www.cnblogs.com/zzq-123456/p/9683252.html
Copyright © 2011-2022 走看看