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)
字符串“PAYPALISHIRING”在给定的行数上以锯齿形模式写入,如下所示:
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:
然后一行一行地读就会得到:“PAHNAPLSIIGYIR”
给出特定行数和原始字符串,请你做出此转换并输出转换后的字符串。
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
算法
可以通过行来排序,我们从左往右遍历字符串,可以很容易的知道每个字母属于哪一行。
合适的行可以通过2个变量来追踪,分别是goingDown
和curRow
(分别表示正确的方向和正确的行)
C++代码
class Solution{
public:
string convert(string s,int numRows){
if(numRows == 1) return s;//特殊情况,size等于1直接输出s
if(numRows > s.size()) return s;//特殊情况,行比size还大也直接输出s
vector<string> rows(numRows);
int curRow = 0;//正确的行
bool goingDown = false;//正确的方向
for(char c : s){
rows[curRow]+=c;
if(curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;//如果到头或者尾了,方向改变
curRow += goingDown ? 1 : -1;//根据方向来进行加减操作
}
string ret;
for(string row : rows){
ret += row;
}
return ret;
}
};