/*
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
*/
#include "iostream"
#include "string"
using namespace std;
class Solution
{
public:
string convert(string s, int numRows)
{
int cols, spare, i, j, part, size = s.size();
if (numRows == 1)
{
return s;
}
part = 2 * numRows - 2; // 没一小部分有多少个
cols = s.size() / part * (numRows - 1); // 有多少整列
spare = s.size() % part; // 散列中多出来多少个
if (spare > 0)
{
cols += 1;
if (spare > numRows)
{
cols += spare - numRows;
}
}
string ans;
char c;
for (i = 0; i < numRows; i++)
{
for (j = 0; j < cols; j++)
{
if (j % (numRows - 1) == 0 && part * (j / (numRows - 1)) + i < size)
{
c = s[part * (j / (numRows - 1)) + i];
cout << c;
ans.push_back(c);
}
else if (j % (numRows - 1) == numRows - i - 1 && part * (j / (numRows - 1)) + 2 * numRows - i - 2 < size)
{
c = s[part * (j / (numRows - 1)) + 2 * numRows - i - 2];
cout << c;
ans.push_back(c);
}
else
{
cout << " ";
}
}
cout << endl;
}
return ans;
}
};
int main()
{
string s;
int numRows;
cin >> s;
cin >> numRows;
Solution so;
string ans = so.convert(s, numRows);
cout << ans << " " << ans.size() << endl;
return 0;
}
【Leetcode】6.Z 字形变换C++(直接排序法)
猜你喜欢
转载自blog.csdn.net/weixin_44936889/article/details/104076630
今日推荐
周排行