首页 > 代码库 > LeetCode 6. ZigZag Conversion

LeetCode 6. ZigZag Conversion

        public string Convert(string s, int numRows)
        {
            if (numRows <= 1 || s.Length == 0)
            {
                return s;
            }

            string res = "";
            int len = s.Length;
            for (int i = 0; i < len && i < numRows; ++i)
            {
                int indx = i;
                res += s[indx];

                for (int k = 1; indx < len; ++k)
                {
                    //第一行或最后一行,使用公式1:  
                    if (i == 0 || i == numRows - 1)
                    {
                        indx += 2 * numRows - 2;
                    }
                    //中间行,判断奇偶,使用公式2或3  
                    else
                    {
                        if (k % 2 == 1)  //奇数位  
                            indx += 2 * (numRows - 1 - i);
                        else indx += 2 * i;
                    }

                    //判断indx合法性  
                    if (indx < len)
                    {
                        res += s[indx];
                    }
                }
            }
            return res;
        }

 

LeetCode 6. ZigZag Conversion