19.1.20 [LeetCode 6]ZigZag Conversion

Medium

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
 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         int group = numRows + numRows - 2;
 5         if (group <=1)return s;
 6         int i, size = s.length();
 7         string ans = "";
 8         for (int i = 0; i < size; i += group)
 9             ans+=s[i];
10         for (int j = 1; j < numRows-1; j++) {
11             for (i = 0; i < size; i += group) {
12                 if(i+j<size)
13                     ans+=s[i+j];
14                 if(i+group-j<size)
15                     ans+=s[i + group - j];
16             }
17         }
18         for (int i = numRows - 1; i < size; i += group)
19             ans+=s[i];
20         return ans;
21     }
22 };
View Code

简单的模拟,坑点在于有类似 numRows=1 的情况

注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
原文地址:https://www.cnblogs.com/yalphait/p/10295029.html