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
问题大意:在行数给定时,写出字符串“PAYPALISHIRING”的Z字形(zigzag)写法,有点像高中物理的沙漏和向前移动的纸带。
解题思路:遍历字符串,设置一个变量cur表示现在纵向的行号,在设置一个布尔变量down作为方向标志(down为真cur++,down为假cur--)。
#include<string> #include<iostream> using namespace std; string convert(string s, int numRows){ if (numRows == 1) return s; string rows[3]; int cur = 0; bool down = true; for (int i = 0; i < s.size(); ++i){ rows[cur] += s[i]; if (cur == 0) down = true; else if (cur == (numRows - 1)) down = false; if (down) cur++; else cur--; } string ans; for (int i = 0; i < numRows; i++) ans += rows[i]; return ans; } int main(){ string s1 = "123456789"; string result = convert(s1,3); cout << "zagzig输出是: " << result << endl; //139246837 getchar(); }