题目描述:
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"
.
这题网上有不少解法,下面是我自己的一种解法:
思想:把zigZig字符串分成一段段,段长是partslen=nRos*2-2。每个段是一个竖线和斜线组成。那么转换成字符串时,分成2种情况,首尾行和中间行
设i是行号,j是段号,则有
首尾行元素对应坐标:j*partslen+i
中间行元素除了包含上面这个坐标的元素外,还要有(j+1)*partslen-i,如图中‘P’的坐标就是2*2-1,当然需要有一些边界判断。
代码如下:
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 if(s.size()<=1||numRows<=1)return s; 5 int partslen=2*numRows-2; 6 int parts=s.size()/(2*numRows-2); 7 string result; 8 for(int i=0;i<numRows;++i) 9 { 10 for(int j=0;j<=parts;++j) 11 { 12 13 if((i==0||i==numRows-1)&&(j*partslen+i)<s.size()) 14 { 15 result.push_back(s[j*partslen+i]); 16 } 17 else if((j*partslen+i)<s.size()) 18 { 19 result.push_back(s[j*partslen+i]); 20 if((j+1)*partslen-i<s.size()) 21 result.push_back(s[(j+1)*partslen-i]); 22 } 23 } 24 25 } 26 return result; 27 } 28 };