LeetCode #6 ZigZag Conversion C# Solution

来源:互联网 发布:中英文在线翻译软件 编辑:程序博客网 时间:2024/05/20 00:51

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)

可能有人不知道ZigZag是什么意思,其实就是给一个字符串,让你按照Z字形来排列,同时要求按给出的行数排列,最后按行输出。
其实就是找规律,向下循环是nRows,斜角线循环是nRows-2。

C# Code    public class Solution    {        public string Convert(string s, int numRows)        {            if (s.Length == 0 || numRows < 2) return s;            string ans = "";            int time = 2 * (numRows - 1);            for (int i = 0; i < numRows; i++)            {                for (int j = i; j < s.Length; j += time)                {                    ans += s[j];                    if (i > 0 && i < numRows - 1)                    {                        if (j + time - 2 * i < s.Length)                        {                            ans += s[j + time - 2 * i];                        }                    }                }            }            return ans;        }    }

这里写图片描述

0 0
原创粉丝点击