码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】ZigZag Conversion

时间:2014-10-07 15:21:03      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   sp   div   c   on   

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

标签:style   blog   color   io   for   sp   div   c   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!