将一个字符串按照ZIGZAG方式打印,举例说明
///nRows:2
///1, 3, 5 step: 2
///2, 4, 6 step: 2
///
///nRows:3
///1, 5, 9 step: 4
///2, 4, 6, 8, 10 step:2 2
///3, 7, 11 step: 4
///
///nRows:4
///1, 7, 13 step: 6
///2, 6, 8, 12, 14 step:4 2
///3, 5 9, 11, 15 step:2 4
///4, 10, 16 step: 6
///
///nRows:5
///1, 9, 17 step: 8
///2, 8, 10, 16, 18 step:6 2
///3, 7, 11, 15, 19 step:4 4
///4, 6, 12, 14, 20 step:2 6
///5, 13, 21 step: 8
///
注意点
- 首尾步长都是(n-1)*2,中间部分的步长变化是(n-i-1)*2和i*2,所以我是首尾与中间部分进行了分别处理
- 要防止越界,tempLoca+i<s.size()和tempLoca<s.size()
- 要注意空串和n==1的特殊情况
- 老兔子代码写太烂,上面一些注意点有可能进行统一处理,^_^
class Solution {
public:
string convert(string s, int nRows) {
string res=s;
if(s != "" & nRows != 1)
{
int location=0;
int tempLoca = 0;
while(tempLoca<s.size())
{
res[location++] = s[tempLoca];
tempLoca += (nRows-1)*2;
}
for(int i=1; i<nRows-1; i++)
{
tempLoca = 0;
for(int j=0;tempLoca+i<s.size();j++)
{
res[location++] = s[i+tempLoca];
tempLoca += j&1?i*2:(nRows-i-1)*2;
}
}
tempLoca = nRows-1;
while(tempLoca<s.size())
{
res[location++] = s[tempLoca];
tempLoca += (nRows-1)*2;
}
}
return res;
}
};