首页 > 代码库 > Leetcode_实现zigzag的转换_20161228
Leetcode_实现zigzag的转换_20161228
#include<iostream>
#include<vector>
#include<string>
void main()
{
using namespace std;
class Solution
{ public: string convert(string s, int numRows)
{
int h2 = s.length();
int lie1 = h2/ numRows; //得到排列的列数
if (h2%numRows != 0)
lie1++;
vector<vector<char>>ret(numRows); //定义二维向量
for (int i = 0; i < numRows;i++)
ret[i].resize(lie1*2); //得到 numRows*lie1的矩阵
int i = 0;
int j = 0;
int i0 = 0;
for (int count = 0; (count < (numRows*lie1 * 2))&&(i0<h2); count++)
{
if (i == 0)
{ //如果行数等于列数就往下加
for (int ii = 0; (ii < numRows) && (i0<h2); ii++)
{
ret[ii][j] = s[i0];
i0++;
}
i = numRows - 1;
j++;
}
if (i == (numRows - 1))
{
for (int ii = numRows - 2; (ii >= 1) && (i0<h2); ii--)
{
ret[ii][j] = s[i0];
j++;
i0++;
}
i = 0;
}
} //将字符串赋值给向量ret
string s1;
char *c;
for (int i1 = 0; i1 < numRows; i1++)
{
for (int j1 = 0; j1 < (lie1 * 2); j1++)
{
if (ret[i1][j1]!=‘\0‘)
{
c = &(ret[i1][j1]);
s1.append(c,1); //每次都将值赋给字符串,这里必须加上1,不然会加其他的东西在s1里面
} // cout << ret[i1][j1];
}
}
return s1;
}
};
Solution A;
string a1 = "ABC";
cout << a1 << endl;
string b;
b = A.convert(a1, 2);
int h1 = b.length();
cout << b<<endl;
system("pause");
}
Leetcode_实现zigzag的转换_20161228