逗比题目ZigZag

这题没有啥难的,画个图想清楚直接坐标访问需要的字符就行了,稍微需要注意的就是最后边界要处理一下

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".

唯一需要搞make clear的就是ZigZag是什么意思:见下图

|  |  |  |  |  |  |
| /| /| /| /| /| /|
|/ |/ |/ |/ |/ |/ |
|  |  |  |  |  |  |
View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    # @return a string
    def convert(self, s, nRows):
        if nRows == 1:
            return s
        factor = 2 * nRows -2
        newS = ""
        for i in range(0, nRows):
            offset = factor - 2 * i
            index = i
            while index < len(s):
                newS += s[index]
                if i != 0 and i != nRows - 1 and (index + offset) < len(s):
                    newS += s[index+offset]
                index += factor
        return newS

 

Share This: 

Leave a Reply

Your email address will not be published. Required fields are marked *