zoukankan      html  css  js  c++  java
  • Leetcode 6. ZigZag Conversion

    Description: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 s, int numRows);

    Link: 6. ZigZag Conversion

    Examples:

    Example 1:
    Input: s = "PAYPALISHIRING", numRows = 3
    Output: "PAHNAPLSIIGYIR"
    
    Example 2:
    Input: s = "PAYPALISHIRING", numRows = 4
    Output: "PINALSIGYAHRPI"
    Explanation:
    P     I    N
    A   L S  I G
    Y A   H R
    P     I
    
    Example 3:
    Input: s = "A", numRows = 1
    Output: "A"
    

    题意理解: 我刚看到这个题,完全不理解什么意思。题意是说给定一个字符串s,把s按照N字形锯齿排列,然后按行输出。这个题解对怎么N排列有详细的例子,很容易懂,理解了是怎么排列的很容易做了。接下来就是找每一行字母下标的规律,第一行和最后一行,每个元素的间隔是numRows + (numRows-2),竖的一画需要numRows个元素,和斜的连接两个竖的,要消耗numRows - 2, 所以到下一个中间隔了interval = 2×numRows - 2和元素。中间的每一行间隔是interval-2*row, interval - (interval-2*row), 两个竖的间距是不变的,总是interval, 中间插入的这个元素的index和所处的行row有关。所以知道了每一行的排列规律,从第一行依次输出就好了。

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

    日期: 2021-04-04 清明节,那边也复活节放假了

  • 相关阅读:
    [数据结构]图的DFS和BFS的两种实现方式
    [算法]两个栈实现一个队列
    [数据结构]手动实现队列
    [数据结构]手动实现栈
    [数据结构]手动实现单链表
    Hive分组取Top K数据
    HBase解决海量图片存储方案
    非结构化数据存储方案
    头条面试题之实现两个线程轮流打印字符串
    [算法]最大连续子数组和,最长重复子串,最长无重复字符子串
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14616741.html
Copyright © 2011-2022 走看看