zoukankan      html  css  js  c++  java
  • 【leetcode】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".

    解题思路:

    这个题目有两种做法:第一种是模拟,也就是说我们可以有几行就开几个数组都存起来,最后合到一起就可以了;另一种方法是找规律。因为第一种比较直观,故代码实现了第一种思路:

    class Solution:
        # @return a string
        def convert(self, s, nRows):
            if nRows == 1:
                return s
            gap = nRows - 2
            res = []
            for i in range(nRows):
                res.append([])
            i = 0
            while i < len(s):
                for j in range(nRows):
                    if i >= len(s):
                        break
                    res[j] += s[i]
                    i += 1
                for j in range(gap,0,-1):
                    if i >= len(s):
                        break
                    res[j] += s[i]
                    i += 1
            ress = ""
            for i in res:
                for j in i:
                    ress += j
            return ress
  • 相关阅读:
    eclipse新 java 文件时自动生成注释
    int占几个字节
    eclipse常用插件
    Asp.net中IsPostBack的实现原理
    Github的入门简介
    Hypertable
    VA01/VA02行项目物料搜索帮助新增页签
    rich_text
    js之Math
    js function参数
  • 原文地址:https://www.cnblogs.com/MrLJC/p/4437530.html
Copyright © 2011-2022 走看看