题意
将一个字符串按照题目中所规定的的规则进行摆放,然后输出新的字符串序列
思路
如题中的例子,我们可以将摆放好的字符串来进行偏移来找出规律:
P A H N
A P L S I I G
Y I R
如上图所示,我们可以发现,第一层之间的字符下标相差 (numRows−1)∗2 ,然后接下来依次递减,递减的程度和层数的奇偶有关系,代码中很详细,直到最后一层,又恢复为 (numRows−1)∗2 .
结果
Your runtime beats 42.85 % of cpp submissions.
代码
class Solution {
public:
string convert(string s, int numRows) {
string str = "";
if(numRows <= 1){
return s;
}
int len = s.length();
for(int i = 0; i < numRows; i++){
int p = (numRows - 1 - i) * 2;
int flag = 0;
for(int j = i;j < len;){
str += s[j];
if(i == numRows - 1) j += (numRows - 1) * 2;
else if(i == 0) j += p;
else if(flag % 2 == 0) j += p;
else j += ((numRows - 1) * 2 - p);
flag++;
}
}
return str;
}
};