【Leetcode】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".

模拟题,要特别注意nRows为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 };

 或者用找规律的方法,但是也需要单独考虑nRow为1的情况。

 1 class Solution {
 2 public:
 3     string convert(string s, int nRows) {
 4         if (nRows < 2) return s;
 5         string ret;
 6         int step = 2 * nRows - 2, n = s.size();
 7         for (int i = 0; i < nRows; ++i) {
 8             for (int j = i; j < n; j += step) {
 9                 ret.push_back(s[j]);
10                 if (i != 0 && i != nRows - 1 && j + 2 * (nRows - i - 1) < n) {
11                     ret.push_back(s[j + 2 * (nRows - i - 1)]);   
12                 }
13             }
14         }
15         return ret;
16     }
17 };
原文地址:https://www.cnblogs.com/dengeven/p/4009266.html