LeetCode6 ZigZag Conversion

题意:

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".   (Easy)

 

分析:

首先是理解题意,题目例子举得不好...起始ZigZag的意思以4举例更易懂一些。

1           7             13

2      6   8        12

3   5      9   11

4          10

读懂了题意,其实就是判断好什么时候向下,什么时候向上即可,我用的vector<string>实现,维护nRows个string,最后拼接在一起。

 

代码:

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         if (numRows == 1) {
 5             return s;
 6         }
 7         vector<string> v(numRows);
 8         int j = 0;
 9         for (int i = 0; i < s.size(); ++i) {
10             if ( (i / (numRows - 1) ) % 2 == 0) {
11                 v[j].insert(v[j].end(), s[i]);
12                 j ++;
13             } 
14             if ( (i / (numRows - 1)) % 2 == 1) {
15                 v[j].insert(v[j].end(), s[i]);
16                 j--;
17             }
18        }
19        string result;
20        for (int i = 0; i < v.size(); ++i) {
21            result += v[i];
22        }
23        return result;
24     }
25 };

 

posted @ 2016-08-02 21:40  wangxiaobao1114  阅读(164)  评论(0编辑  收藏  举报