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

LeetCode Online Judge 题目C# 练习 - ZigZag Conversion

2012-10-23 05:09 513 查看
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 static string ZigZagConversion(string s, int nRows)
{
if (nRows == 1)
return s;

int currRow;
bool goDown;
string ret = "";

for (int r = 1; r <= nRows; r++)
{
currRow = 1;
goDown = true;
for (int i = 0; i < s.Length; i++)
{
if (currRow == r)
ret += s[i];

if (currRow != nRows && goDown)
currRow++;
else if (currRow == nRows)
{
currRow--;
goDown = false;
}
else if (currRow != 1 && !goDown)
currRow--;
else if (currRow == 1)
{
currRow++;
goDown = true;
}
}
}

return ret;
}


代码分析:

  分几行就撸几次,每次都从头到尾撸string s 一次。 一个currRow,每当currRow hit 当前的行r, ret += s[i]; 一个goDown flag 看着currRow该++还是--;

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