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
版权声明:本文标题:[勇者闯LeetCode] 6. ZigZag Conversion 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1694387573a251475.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论