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 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)Shocould return"Pahnaplsiigyir".
After a string is represented in the font "of", it is combined by each line to output a new string.
I learned the O (n) algorithm in my blog.
Create nrows strings, copy the coordinates of S to each string, and use pushback. The output of the last append connection. The Code is as follows:
class Solution { public: string convert(string s, int nRows) { if (nRows <= 1 || s.length() < 2) return s; string *s_arr = new string[nRows]; int nCount = 2 * (nRows - 1); // 每个循环的轮回 也就是 2倍的nRows - 2 for (int i = 0; i < s.length(); ++i) { s_arr[nRows - 1 -abs(nRows - 1 - (i%nCount))].push_back(s[i]); } string str_result; for (int i = 0; i < nRows; ++i) str_result.append(s_arr[i]); return str_result; } };
Coordinate matching is the key, and the logic thinking of mathematics is indeed strong. You can give an example of four rows.
Question 6 of leetcode -- zigzag Conversion