admin 管理员组

文章数量: 1087818

[勇者闯LeetCode] 6. ZigZag Conversion

[勇者闯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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Information

  • Tags: String
  • Difficulty: Medium

Solution

找规律
1. 所有行的重复周期都是 2 * (nRows - 1)
2. 对于首行和末行之间的行,还会额外重复一次,重复周期是 2 * (nRows - i - 1),其中i表示第i行。

class Solution(object):def convert(self, s, numRows):""":type s: str:type numRows: int:rtype: str"""if numRows < 2: return sans = ""for i in range(0, numRows):for j in range(i, len(s), 2*(numRows-1)):ans += s[j]if i > 0 and i < numRows-1 and (j + 2 * (numRows-i-1)) < len(s):ans += s[j + 2 * (numRows-i-1)]return ans

本文标签: 勇者闯LeetCode 6 ZigZag Conversion