美文网首页
6. ZigZag Conversion

6. ZigZag Conversion

作者: Chiduru | 来源:发表于2019-03-13 12:11 被阅读0次

【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);
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

【Idea】

  1. 定义numRows长的list, 每个元素为 ‘’ 空字符串,对应题干中的每列,用于存储遍历时对应的字符;
  2. 对于给定string s, 对其中的字符挨个遍历,取他的index进行计算,映射并加入到对应的列;
    【核心】从字符串中的index到对应组的映射。
    通过example可知,字符循环中,每2(numRows-1)为一个循环,其中又分两部分:
    (1)由 0~(numRows-1), 直接对 2(numRows-1)取余即可得对应列的下标;
    (2)由(numRows-1)~ 2(numRows-1), 直接取余会超出列数组的范围,需要做处理: 2(numRows-1) - (i % (2numRows-2));
    以上两部分可以通过对字符index和numRows-1 数值比较大小,作为条件;
  3. ‘’.join(chars)

【Solution】

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows <= 1 or numRows >= len(s):
            return s
        length = len(s)
        chars = ['' for i in range(numRows)]
        for i in range(length):
            if i % (2*numRows-2) < numRows-1:
                index = i % (2*numRows-2)
                chars[index] += s[i]
            else:
                index = (2*numRows-2) - (i % (2*numRows-2))
                chars[index] += s[i]
        res = ''
        return ''.join(chars)

相关文章

网友评论

      本文标题:6. ZigZag Conversion

      本文链接:https://www.haomeiwen.com/subject/azezpqtx.html