![【Leetcode】6.Z 字形变换C++(找规律法) 【Leetcode】6.Z 字形变换C++(找规律法)](/default/index/img?u=aHR0cHM6Ly93d3cuaWNvZGU5LmNvbS9pL2xsLz9pPTIwMjAwMTIzMTgwMTA2OTExLnBuZz8sdHlwZV9abUZ1WjNwb1pXNW5hR1ZwZEdrLHNoYWRvd18xMCx0ZXh0X2FIUjBjSE02THk5aWJHOW5MbU56Wkc0dWJtVjBMM2RsYVhocGJsODBORGt6TmpnNE9RPT0sc2l6ZV8xNixjb2xvcl9GRkZGRkYsdF83MA==)
![【Leetcode】6.Z 字形变换C++(找规律法) 【Leetcode】6.Z 字形变换C++(找规律法)](/default/index/img?u=aHR0cHM6Ly93d3cuaWNvZGU5LmNvbS9pL2xsLz9pPTIwMjAwMTIzMTgwMDUwMTMxLnBuZw==)
/*
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
*/
#include "iostream"
#include "string"
#include "vector"
using namespace std;
class Solution
{
public:
string convert(string s, int numRows)
{
if (numRows == 1)
return s;
int len = s.length();
int step = 2 * numRows - 2; // 间距
int curor, sub;
string ans;
for (int i = 0; i < numRows; i++)
{
curor = i;
sub = 2 * i;
while (curor < len)
{
ans += s[curor];
sub = step - sub;
curor += (i == 0 || i == numRows-1) ? step : sub;
}
}
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++(找规律法) 【Leetcode】6.Z 字形变换C++(找规律法)](/default/index/img?u=aHR0cHM6Ly9wcm9maWxlLmNzZG5pbWcuY24vOS8yLzQvM193ZWl4aW5fNDQ5MzY4ODk=)
Memory逆光
发布了71 篇原创文章 · 获赞 128 · 访问量 1万+
私信
关注