您的位置:首页 > 其它

LeetCode解题记录(6)

2015-04-13 13:54 337 查看

LeetCode解题记录(6)

目录

LeetCode解题记录6
目录

前言

正文
题目

解法一

前言

我将慢慢开始做LeetCode上的题,并做解题记录发布在这里。我每题会给出一到多个解法,记录思考过程。我算法巨烂,是想通过这种方式稍微补补,基本功和我一样差的小伙伴可以和我一起共勉,有大神路过可以指点一二,我感激不尽。解题的最底要求是能通过LeetCode的检测,我不会丧病的为了各种提高效率在一个题上纠缠不休,所以最终解法可能也不怎么样,大家看看就好~编程语言一律采用C#。题解代码会按编号发布到我的GitHub上(仅保留最终解法)。

正文

题目

problem005:

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 class Solution {
public string Convert(String s, int nRows) {
StringBuilder result = new StringBuilder();
if(s.Length < nRows || nRows == 1) return s;
int sumStep = 2 * (nRows - 1);
int point = 0;
int step1 = 0;
int step2 = 0;
bool flag = true;
for (int i = 0; i < nRows; ++i)
{
point = i;
step1 = sumStep - 2 * i;
if (step1 == 0) step1 = sumStep;
step2 = sumStep - step1;
if (step2 == 0) step2 = sumStep;
flag = true;
while (point < s.Length)
{
result.Append(s[point]);
if (flag)
{
point += step1;
}
else
{
point += step2;
}
flag = !flag;
}
}
return result.ToString();
}
}


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