题目

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 s, int numRows);

Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:

Input: s = “A”, numRows = 1
Output: “A”

Constraints:

1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ‘,’ and ‘.’.
1 <= numRows <= 1000

解法:模拟

对于行数是 n 的情况:

对于第一行和最后一行,是公差为 2(n−1)的等差数列,首项是 0 和 n−1;
对于第 i 行(0所以我们可以从上到下,依次打印每行的字符。

时间复杂度O(n),空间复杂度O(1)

  1. class Solution {
  2. public:
  3. string convert(string s, int n) {
  4. string ans;
  5. if (n == 1) return s;
  6. for (int i = 0; i < n; i++) {
  7. if (i == 0 || i == n - 1) {
  8. for (int j = i; j < s.size(); j += 2 * n - 2) {
  9. ans += s[j];
  10. }
  11. } else {
  12. for (int j = i, k = 2 * n - 2 - i; j < s.size() || k < s.size(); j += 2 * n - 2, k += 2 * n - 2) {
  13. if (j < s.size()) ans += s[j];
  14. if (k < s.size()) ans += s[k];
  15. }
  16. }
  17. }
  18. return ans;
  19. }
  20. };