/**
* 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".
*/
第一列 | 第二列 | 第三列 | 第四列 | 第五列 | 第六列 | 第七列 |
---|---|---|---|---|---|---|
P 0 | I 6 | N 12 | ||||
A 1 | L 5 | S 7 | I 11 | G 13 | ||
Y 2 | A 4 | H 8 | R 10 | |||
P 3 | I 9 |
zigzag形像一个竖着的 Z 字
拼成的字符串有关键的两个公式:
1. 第一行和最后一行获取字符的位置公式: nRows*2 -2
2. 中间的每一行会多一个字符,多余字符的位置: 2 * nRows - 2 - 2 * row
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string convert(string s, int nRows)
{
if (s.empty() || nRows <= 0 || nRows >= s.length())
return s;
int len = s.length();
int step = nRows * 2 - 2;
int i = 0;
string rs = "";
int tmp = 0;
for (int row = 0; row < nRows; row++)
{
for (i = row; i < len; i+=step)
{
rs += s[i];
if (row == 0 || row == nRows - 1)
continue;
tmp = i + step - 2 * row;
if (tmp < len)
rs += s[tmp];
}
}
return rs;
}
int main()
{
cout << convert("PAYPALISHIRING", 3);
system("pause");
return 0;
}