Topic describes
Arrange a given string s in zigzagging from top to bottom and left to right, numRows, according to the given number of rows. For example, if the string “PAYPALISHIRING” is set to 3 rows, it will look like this:
PAHNAPLSIIGYIR Then your output needs to be read line by line from left to right, producing A new string, such as “PAHNAPLSIIGYIR”.
The sample
Example 1: Enter: s = “PAYPALISHIRING”, numRows = 3 Output: “PAHNAPLSIIGYIR”
Example 2: Enter: s = “PAYPALISHIRING”, numRows = 4 Output: “PINALSIGYAHRPI”
Source: LeetCode link: leetcode-cn.com/problems/lo…
implementation
Rule:
- NumRows (n for short) represents the number of rows and the maximum number of elements in a column, n=3, so the 0th column has three elements
- As you can see from the example, given n rows, column 0 has n elements, followed by n minus 2 columns containing one element. These n-1 columns are considered as a combined column, and it can be known that the elements contained in a combined column are N +(n-2)=2n-2
- At this point, you can process the string, iterate over the string, and divide the elements of the string into 2 cases
- The first case is like column 0, traversing from the top down
- The second case is followed by n minus 2 columns of one element, traversed from the bottom up
For example: So if you take the string “PAHNAPLSIIGYIR” the first case is PAY ALI HIR NG in which case the remainder is the number of rows for each element and the second case is PSI in which case, if you go down, the number of rows is the opposite of the current index, the remainder for each element is 2n-2, The number of rows is 2n minus 2 minus the remainder is the number of rows.
char *convert(char * s, int numRows)
{
if (s == NULL) {
return NULL;
}
if (strlen(s) == 1 || numRows <= 1) {
return s;
}
int idx = 0;
char *res = (char*)malloc(sizeof(char) * (strlen(s) + 1));
int n = 2 * numRows - 2;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < strlen(s); j++) {
if (j % n == i || j % n == n - i) {
res[idx++] = s[j];
}
}
}
res[idx] = '\ 0';
return res;
}
Copy the code