(算法分析Week10)ZigZag Conversion[Medium]
2017-11-09 13:31
405 查看
6.ZigZag Conversion[Medium]
题目来源Description
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”.
Solution
zigzag是锯齿型的意思,一开始没明白题目要干什么,但是仔细研究样例应该能理解。举几个例子:nRows为2时,字符串坐标变成zigzag的走法就是: 0 2 4 6 1 3 5 7 nRows取3时: 0 4 8 1 3 5 7 9 nRows取4时: 0 6 12 1 5 7 11 13 2 4 8 10 14 3 9 15
比较直观的想法是用一个字符串数组string[rows]来存储每一行,用一个delta表示正向还是反向,即上图中从第一行到最后一行还是最后一行到第一行。最后把字符串数组拼接起来就可以了。
不过可以尝试找一下规律,发现所有行的重复周期都是 (2 * nRows - 2)。
对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 (2 * nRows - 2 - 2 * i)
Complexity analysis
O(n²)Code
class Solution { public: string convert(string s, int nRows) { if (nRows <= 1 || s.length() == 0) return s; string res = ""; int len = s.length(); for (int i = 0; i < len && i < nRows; ++i) { int indx = i; res += s[indx]; for (int k = 1; indx < len; ++k) { if (i == 0 || i == nRows - 1) { indx += 2 * nRows - 2; } else { if (k % 2 == 1) indx += 2 * (nRows - 1 - i); else indx += 2 * i; } if (indx < len) { res += s[indx]; } } } return res; } };
Result
相关文章推荐
- (算法分析Week10)Letter Combinations of a Phone Number[Medium]
- (算法分析Week6)Longest Palindromic Substring[Medium]
- 算法分析与设计丨第四周丨LeetCode(8)——Binary Tree Level Order Traversal(Medium)
- 算法设计与分析(8)-- Container With Most Water(难度:Medium)
- (算法分析Week11)Swap Nodes in Pairs[Medium]
- (算法分析Week1)Different Ways to Add Parentheses[Medium]
- (算法分析Week18)Gray Code[Medium]
- (算法分析Week7)Divide Two Integers[Medium]
- 算法分析与设计丨第四周丨LeetCode(7)——Find Bottom Left Tree Value(Medium)
- .ZigZag Conversion题目分析
- (算法分析Week16)Remove Nth Node From End of List[Medium]
- 算法分析与设计丨第一周丨LeetCode(2)——Different Ways to Add Parentheses(Medium)
- (算法分析Week6)Container With Most Water[Medium]
- 算法分析与设计丨第三周丨LeetCode(6)——Find Largest Value in Each Tree Row(Medium)
- (算法分析Week15)01Matrix[Medium]
- week4-leetcode #6-ZigZag Conversion[Medium]
- (算法分析Week10)Maximum Swap[Meduim]
- 算法分析与设计丨第十四周丨LeetCode(18)——Maximum Subarray(Medium)
- (算法分析Week12)Count Numbers with Unique Digits[Medium]
- 算法设计与分析(6)-- ZigZag Conversion(难度:Medium)