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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
思路:
1. 设计两个操作对象:一个是给定的string,一个是zigzag存放的vector< string>,问题就是让把string按照zigzag的方式存入。有两种方式:一是根据vector< string>中的位置来计算在string中对应的位置;另一种是根据string中的位置去找在vector< string>中的位置。这里,由于string的位置是一维的且已知,所以用第二种方式。
2. 看一下zigzag是怎么回事:
0 8 16
1 7 9 15 17
2 6 10 14 18
3 5 11 13 19
4 12 20
一看就知道这是一个循环,numRows=5,所以0-4直接放vector< string>,5-7则需要放入8-i的位置,就是一个简单的数学技巧。也就是有两个区间:区间[0,4]和[5,7]。后面的数都这么循环,循环周期是8,这个用编程语言表示,就是对i%8即可把任意数都映射到[0,4]或[5,7]这两个区间来!
class Solution {
public:
string convert(string s, int numRows) {
//
if (numRows==1|| s.size()<=numRows) return s;//这个edge case一定需要,不然,当numRows=1,step=0,idx=i%0就出错,所以考虑numRows=1是对后面的操作加保护!
vector<string> tmp(numRows,"");
int step=2*numRows-2;
for(int i=0;i<s.size();i++){
int idx=i%step;
if(idx>=0&&idx<numRows){//zigzag:从上往下
tmp[idx].push_back(s[i]);
}else//zigzag:从下往上
tmp[step-idx].push_back(s[i]);
}
string res;
for(auto ss:tmp){
res+=ss;
}
return res;
}
};