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".
代码分析:
分几行就撸几次,每次都从头到尾撸string s 一次。 一个currRow,每当currRow hit 当前的行r, ret += s[i]; 一个goDown flag 看着currRow该++还是--;
马勒隔壁,终于完了。
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该++还是--;
马勒隔壁,终于完了。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Word Search
- LeetCode Online Judge 题目C# 练习 - Gray Code
- LeetCode Online Judge 题目C# 练习 - Implement strStr()
- LeetCode Online Judge 题目C# 练习 - Add two number
- LeetCode Online Judge 题目C# 练习 - Longest Substring Without Repeating Characters
- LeetCode Online Judge 题目C# 练习 - Reverse Nodes in k-Group
- LeetCode Online Judge 题目C# 练习 - 4SUM
- LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal II
- LeetCode Online Judge 题目C# 练习 - Combination
- LeetCode Online Judge 题目C# 练习 - N-Queens
- LeetCode Online Judge 题目C# 练习 - Add Binary
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- LeetCode Online Judge 题目C# 练习 - Two Sum
- LeetCode Online Judge 题目C# 练习 - Count and Say
- LeetCode Online Judge 题目C# 练习 - Minimum Window Substring
- LeetCode Online Judge 题目C# 练习 - Remove Element
- LeetCode Online Judge 题目C# 练习 - Decode Way
- LeetCode Online Judge 题目C# 练习 - Plus One
- LeetCode Online Judge 题目C# 练习 - Search Insert Position
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II