leetcode之ZigZag Conversion

来源:互联网 发布:java 创建控制台程序 编辑:程序博客网 时间:2024/05/16 17:20

Zigzag:即循环对角线结构(

0   8   16   1  79  1517   2 6 10 14 18   35  1113  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;
}





0 0
原创粉丝点击