Contents

LeetCode--ZigZagConversion

Contents

其实这道题目困扰了好久,试了很多的方法,发现都不得其解。当我今天试着看看别人是怎么做的时候意外的发现竟然有大神写出如此简洁的答案,细细一品,才发现原来是自己把问题想复杂了,然后一直在绕弯路。

http://www.cnblogs.com/sanghai/p/3632528.html

我贴下LeetCode的题目:

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)

/images/zigzagconversion_2.png

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

分析:

/images/zigzagconversion_3.png

向下循环:numRows

斜角线循环:numRows-2(减去首尾两个端点)

重复 …

C#代码如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public string Convert(string s, int numRows) {
            if (numRows == 1||s.Length<=1)
            return s;
        int i=0,j,gap = numRows - 2;
        string[] str=new string[numRows];
        while(i<s.Length)
        {
            for (j = 0; i < s.Length && j < numRows; j++) str[j] += s[i++].ToString();
            for (j = gap; i < s.Length && j > 0; j--) str[j] += s[i++].ToString();
        }
        string temp = "";
        for (i = 0; i < numRows; i++)
        {
            temp += str[i];
        }
        return temp;
}