Description:
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"
.
题目说给定一个字符串s和数字numRows,s是几个单词组成,numRows是单词个数。s是由这几个单词按照Z字形的书写规则组成的,我们要做的就是根据给定的s和numRows恢复出正常的从左到右的单词书写顺序。
思路:
设置一个string类型的数组words,元素个数为numRows。我们从words[0]开始到words[numRows-1]下标递增规定为正方向,下标递减规定为反方向。
1.从words[0]当words[numRows-1]我们依次填写s中的字符,
2.然后再从words[Rows-1]到words[0]依次填写s中的字符。
3.不断重复1和2,直到全部填写完s中的字符。
class Solution { public: string convert(string s, int numRows) { if(numRows==1) return s; string words[numRows]; string res; int count=0; bool forward=true,reverse=false; for(int i=0;i<s.length();i++){ if(forward){ words[count]=words[count]+""+s[i];//此处为words[count] += ""+s[i]时有问题,如果有人知道请指教一下 count++; if(count==numRows){ count-=2; forward=false; reverse=true; } } else if(reverse){ words[count]=words[count]+""+s[i]; count--; if(count<0){ count+=2; reverse=false; forward=true; } } } for(int j=0;j<numRows;j++){ res+=words[j]; } return res; } };