Zigzag:即循环对角线结构(
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
)
根据上图创建N个string型变量。
然后给每行的string的第一个赋值
然后给斜线部分赋值。
// test4ZigZigConversion.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
using namespace std;
string convert(string s, int nRows);
int _tmain(int argc, _TCHAR* argv[])
{
string res = convert("PAYPALISHIRING", 3);
return 0;
}
string convert(string s, int nRows)
{
if (nRows == 1)
return s;
string* res = new string[nRows];
string result="";
int length = s.size();
int i = 0, j = 0;
while (i<length)
{
for (j = 0; j < nRows && i<length; j++)
res[j] = res[j] + s[i++];
for (j=nRows-2; j > 0 && i < length; j--)
res[j] = res[j] + s[i++];
}
for (j = 0; j < nRows; j++)
result = result + res[j];
return result;
}