題目
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 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"
.解題思路
這個是個純粹找規律的題,其他沒啥特殊的。下面的例子nRows=4;
找規律按照數組小標開始,尋找下標出現的規律,
1. 第一行和最後一行相鄰元素下標之差爲 2*nRows-2;
2. 除過第一行和最後一行,其餘行要多一個元素,該元素出現的下標和行號有關,比如5 = 1 + 6 - 2,可以總結出規律爲 j + 2*nRows-2 - 2*i;
關於 i 和 j 看以看下面的代碼。
代碼實現
class Solution {
public:
string convert(string s, int nRows) {
if(nRows <= 1) return s;
int base = 2*nRows-2;
string ret;
int n = s.size();
for(int i=0; i<nRows; ++i){
for(int j=i; ; j += base){
if(j>=n) break;
ret.append(1,s[j]);
if(i==0 || i==nRows-1) continue;
int temp = j + base - 2*i;
if(temp <s.size()){
ret.append(1,s[temp]);
}
}
}
return ret;
}
};
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.