您的位置:首页 > 编程语言 > C#

LeetCode #6 ZigZag Conversion C# Solution

2016-04-16 10:25 567 查看
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;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: