zoukankan      html  css  js  c++  java
  • leetcode6:Zigzag Conversion@Python

    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".

    首先明白题意,给出一个字符串,按照之字形(Zigzag)排列成矩形,将矩阵每一行连接起来构成一个字符串。

    将矩阵压缩得到:

     1 #-*-coding:utf-8-*-
     2 
     3 class Solution(object):
     4     def convert(self, s, numRows):
     5         """
     6         :type s: str
     7         :type numRows: int
     8         :rtype: str
     9         """
    10         if numRows == 1:
    11             return s
    12         zigzag = ['' for i in range(numRows)]  # 初始化zigzag为['','','']
    13         row = 0                                # 当前的行数
    14         step = 1                               # 步数:控制数据的输入
    15         for c in s:
    16             if row == 0:
    17                 step = 1
    18             if row == numRows - 1:
    19                 step = -1
    20             zigzag[row] += c
    21             row += step
    22         return ''.join(zigzag)
  • 相关阅读:
    web框架本质及第一个Django实例
    jQuery练习题HTML文件
    jQuery快速入门
    前端之JS
    前端基础之HTML
    前端基础之css
    并发编程之 协程
    Linux目录结构详解
    第三周 time库
    网络打印机拒绝访问,无法连接处理方法汇总
  • 原文地址:https://www.cnblogs.com/mzct123/p/5914383.html
Copyright © 2011-2022 走看看