ZigZag Conversion
Difficult:Medium
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 RAnd 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"
.
分析:
问题就是要Z字型输出字符串。
我的实现方法是按要求的行数创建临时的字符串(例如当行数等于3时有s1、s2、s3三个字符串),遍历输入的字符串的时候,按Z字型的顺序把每一位字符放接到临时字符串后边(比如第1个字符接s1后面,第2个接s2,第3个接s3,第4个就又接到s2,第5个接s1,第6个接s2.....),最后再把临时字符串接在一起就好了
string convert(string s, int numRows) {
vector<string> v_result;
for (int i = 0; i < numRows; i++){
v_result.push_back("");//按行数生成临时字符串
}
int step = 1;//初始步进1,步进为1或-1
if (numRows < 2)//如果行数为1则步进为0
step = 0;
int current = 0;
for (int i = 0; i < s.size(); i++){
stringstream stream;
stream << s.at(i);
string tmp = stream.str();
v_result.at(current).append(tmp);//接到相应的临时字符串后面
current = current + step;//加上步进
if (current == 0 || current == numRows - 1)//当current为0或行数时,反转步进
step = step*-1;
}
string result = "";
for (int i = 0; i < numRows; i++){
result.append(v_result.at(i));
}
return result;
}