LeetCode 6 ZigZag

主要是一个Z字形状


0    10

1   911

2  8 12

3 7  13

46   14

5     15。。。。。这样一个形状

因为只需要横向顺序,所以横向压缩就好

上面变成这样


0,  ,10

1,9,11

2,8,12

3,7,13

4,6,14

5,  ,15

这样的话只需要把数组纵向存储然后空出奇数行首位并注意顺序即可

c# code

public class Solution
{
    public string Convert(string s, int numRows)
    {
        if (numRows == 1 || s.Length <= numRows)
            {
                return s;
            }
            string ret = "";
            if (numRows == 2)
            {
                for (int i = 0; i < s.Length && 2 * i < s.Length; i++)
                {
                    ret += s[2 * i];
                }
                for (int i = 0; i < s.Length && 2 * i + 1 < s.Length; i++)
                {
                    ret += s[2 * i + 1];
                }
            }
            else
            {
                char[,] c = new char[numRows, //s.Length % (numRows * 2 - 2) == 0 ? s.Length / (numRows * 2 - 2) :
                    (s.Length / (numRows * 2 - 2) + 1) * 2];
                int q = numRows < 3 ? 1 : numRows - 1;
                int index = 0, row = 0, col = 0;
                while (index < s.Length)
                {
                    if (col % 2 == 0)
                    {
                        for (row = 0; row < numRows && index < s.Length; row++)
                        {
                            c[row, col] = s[index];
                            index++;
                        }
                        col++;
                    }
                    else
                    {
                        for (row = numRows - 2; row > 0 && index < s.Length; row--)
                        {
                            c[row, col] = s[index];
                            index++;
                        }
                        col++;
                    }
                }
                for (int i = 0; i < c.GetLength(0); i++)
                {
                    for (int j = 0; j < c.GetLength(1); j++)
                    {
                        if (c[i, j] != '\0')
                        {
                            ret += c[i, j];
                        }
                    }
                }
            }
            return ret;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值