读题心路历程:读了三遍题之后,嗯......这道题,怎么说呢,读不懂题啊。第四遍,嗯...,我好像明白点了,可是这和 z 有啥关系呀?这不是 N 吗?这个题具体怎么说呢?举个例子:
输入字符串 s="ABCDEFGHI",numRows=3
①首先按照N形写一遍:
②这种倒Z型,也就是N型排布之后,实际再按行输出,也就是输出"(AEI)(BDFH)(CG)" ,这就是这道题的意思。
解题思路:
感觉这道题不是很困难,还是以上边举的例子来看。因为numRows=3,所以其实做题的时候可以不去看N型还是什么Z型,可以直接看成这样的:
就遍历字符串就行了感觉,当遍历的行数等于题目给定的行数的时候,就回一行遍历。大概思路就是这样了,感觉这道题完全体现在你的STL容器用的怎么样。
代码如下:
string convert(string s, int numRows) {
//首先如果行数为1,那么就一行,直接return就可以了。
if(numRows==1) return s;
//然后需要定义一个存放string类型的vector容器,初始化开辟空间numRows个
vector<string> str(numRows);
//然后就利用上下遍历的思路遍历一遍。
int aim = 1;
int currraw = 0;
for(int i=0;i<s.size();i++){
//在第currraw个空间增加字符s[i]
str[currraw].push_back(s[i]);
//currraw行数增加,向上或向下遍历
currraw += aim;
//等遍历到第currraw行或者第一行的时候就需要把遍历方向aim改为相反的方向
if(currraw == 0||currraw == numRows-1){
aim = -aim;
}
}
string ans;
for(int i = 0;i<str.size();i++){
ans+=str[i];
}
return ans;
}