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 R
And 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"
.
题目的意思说的不是很清楚,特别是当两行的时候到底怎么样才是锯齿状。
第一次写的时候对题目理解错了,是锯齿状不是间隔那个样子的,所以结果比较奇怪。
第二次写的时候自己偷懒把齿全都放在了上面,测试在两行锯齿状的时候没有通过,应该齿是一上一下的。
而且把row和column搞混了(可能是英语渣的原因吧,笑哭),导致最后出现了runtime error。
出现runtime error大多是数组越界或者是除了零。
https://blog.csdn.net/dreambyday/article/details/54880616
class Solution { //zigzag锯齿状的 //看了别人的答案之后,锯齿状的意思是一列有多个,接下来的一列只有一个? //可能是自己的理解出现了偏差吧 public: string convert(string s, int numRows) { vector<string> strs; for(int i=0;i<numRows;i++){ string temp=""; strs.push_back(temp); } int length=s.length(); int column=0; int row=0; for(int i=0;i<length;){ if(row%2==0){ for(;row<numRows;){ strs[row].push_back(s[i]); row=(row+1)%numRows; //row++; i++; } } else if(row%2==1){ strs[numRows/2].push_back(s[i]); //row++; row=(row+1)%numRows; i++; } } s.clear(); for(int i=0;i<numRows;i++){ s.append(strs[i]); } return s; } };
(以上的代码是未能通过测试的)
在写代码的时候最先要把最简单的情况考虑到,分类讨论嘛。
在看了他人的代码之后,发现自己对于题目的理解确实存在偏差,拘泥于题目给出的例子。锯齿状就把他想象成那种斜斜的锯齿好啦,到了第一行往下折,到了最后一行往上折不就很ok了嘛
更改之后的代码。
class Solution { //zigzag锯齿状的 //看了别人的答案之后,锯齿状的意思是一列有多个,接下来的一列只有一个? //可能是自己的理解出现了偏差吧 public: string convert(string s, int numRows) { //one line if(numRows<=1){ return s; } vector<string> strs; int length=s.length(); for(int i=0;i<numRows;i++){ string temp=""; strs.push_back(temp); } int row=0; int step=0; for(int i=0;i<length;i++){ strs[row].push_back(s[i]); if(row==0) step=1; else if(row=numRows-1) step=-1; row=row+step; } string result; for(int i=0;i<numRows;i++){ result.append(strs[i]); } return result; } };原作者在代码中是先将s的内容清空,之后又把新的内容放到s内,最终返回s,可以说是很好的编程习惯,内存节约一点是一点。