Leetcode | ZigZag Conversion
Problem:
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 NA P L S I I GY I RAnd 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".
Thinking:
(1) read the meaning of the question, rearrange the strings according to the "Z" shape, and then output the strings by line link.
(2) There is no idea of disintegration. You can list a few simple examples to find a rule.
I. Sorting of 1 to n in two rows
1 3 5 7 9...
2 4 6 8 10...
Ii. Sorting of 1 to n in three rows
1 5 9...
2 4 6 8 10...
3 7 11...
Iii. Sorting of 1 to n in four rows
1 7 13...
2 6 8 12 14...
3 5 9 11 15...
4 10 16...
Is this rule true? If not, you can continue to write 5 rows. Soon you can find the rule. This is a solution to the problem. When we encounter a difficult problem, let's first consider the simple situation to see if we can find the rule. By writing out these special cases, we can find the following rule. Here we assume we are divided into m rows:
1. the I-th row starts with I.
2 The interval between two numbers in the I row is 2 (I-1), 2 (m-I) Alternate
Code:
class Solution {public: string convert(string s, int nRows) { int length = s.size(); if((nRows==1)||(nRows>=length)) return s; string result; for(int i=0;i