ZigZag Conversion

来源:互联网 发布:pdf.js不支持ie11 编辑:程序博客网 时间:2024/05/18 01:05

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

public class Solution {    public string Convert(string s, int numRows) {        if(numRows<2 || s.Length<=numRows)            return s;        var arr = new StringBuilder[numRows];            for (var j = 0; j < numRows; ++j)                arr[j] = new StringBuilder("");        int i = 0, row = 0;        while(i<s.Length)        {            for(row=0; row<numRows&&i<s.Length; ++row)            {                arr[row].Append(s[i++]);            }            for(row=numRows-2; row>0&&i<s.Length;--row)            {                arr[row].Append(s[i++]);            }        }        StringBuilder ret = new StringBuilder("");        for(i=0; i<numRows; ++i)        {            ret.Append(arr[i].ToString());        }        return ret.ToString();    }}
0 0