首页 > 其他 > 详细

【Leetcode】ZigZag Conversion

时间:2014-10-07 14:23:43      阅读:268      评论:0      收藏:0      [点我收藏+]

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".

模拟题,要特别注意k为1时的特殊情况处理。

 1 class Solution {
 2 public:
 3     string convert(string s, int nRows) {
 4         vector<string> v(nRows);
 5         string ret;
 6         bool down = true;
 7         int n = s.size();
 8         int k = 0;
 9         for (int i = 0; i < n; ++i) {
10             if (down) {
11                 v[k].push_back(s[i]);
12                 ++k;
13                 if (k == nRows) {
14                     k = max(0, nRows - 2);
15                     if (k > 0) {
16                         down = false;
17                     }
18                 }
19             } else {
20                 v[k].push_back(s[i]);
21                 --k;
22                 if (k == 0) {
23                     down = true;
24                 }
25             }
26         }
27         for (int i = 0; i < nRows; ++i) {
28             int m = v[i].size();
29             for (int j = 0; j < m; ++j) {
30                 ret.push_back(v[i][j]);
31             }
32         }
33         return ret;
34     }
35 };

 

【Leetcode】ZigZag Conversion

原文:http://www.cnblogs.com/dengeven/p/4009266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!