题目链接
思路:找规律
特殊情况:
- 给定的行数为1,返回原字符串
- 原字符串的长度小于给定的行数,返回原字符串 注意:这个条件不容易想到
一般情况:用另一个数组,一行一行的存储每行的字符。找到字符与字符之间下标的关系。
/%
假设输入串为: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15;给定行数为:4;排列为:
0 6 12
1 5 7 11 13
2 4 8 10 14
3 9 15
其中共有6(=所给行数*2-2)种不同位置,分别是0,1,2,3,4,5.
其中,0-6,1-7,5-11,2-8,4-10,3-9之间的距离都是6.并且5与1的关系为6-1.
这样在遍历的时候只需遍历所给行的行数,再添加一个while循环下标增加6,.......,
将当前遍历到的字符加入到另一个数组中。最后输出该数组。
这个例子相当于输入的字符串的下标。
%/
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
int size = numRows*2-2;//size种不同的位置
string ans = "";//存储当前遍历的字符的字符串
if(numRows == 1|| len <= numRows) return s;//特殊情况
for(int i = 0; i < numRows; i++)//一般情况
{
if(i == 0 || i == numRows-1) {//如果在第一行或者最后一行,下标直接加size
int index = i;
while(1)
{
ans.push_back(s[index]);
index += size;
if(index >= len) break;//下标越界就退出
}
} else {//如果在中间行
int index1 =i, index2 = size - i;//有两种位置的字符,下标分别加size
while(1)
{
if(index1 < len)//先判断是否越界存储
ans.push_back(s[index1]);
if(index2 < len)
ans.push_back(s[index2]);
index1 += size;
index2 += size;
if(index1 >= len) break;
}
}
}
return ans;
}
};