马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Z 字形变动,算法思路整理
https://leetcode.cn/problems/zigzag-conversion/
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右举行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串举行指定行数变动的函数:
- 不擅长打印图形,我将把所有矩阵和一维坐标的映射关系都学习一遍
- class Solution {
- public:
- string convert(string s, int numRows) {
- int s_len = s.size();
- if (s_len <= numRows || s_len <= 1||numRows==1) {
- return s;
- }
- int T = numRows + numRows - 2;
- int T_length = 1 + numRows - 2;
-
- int T_num = s.size() / T + 1;
- int numCols = T_num * T_length;
- vector<vector<char>> ch(numRows, vector<char>(numCols));
- int index_s = 0;
- for (int i = 0; i < numCols; i++) {
- for (int j = 0; j < numRows; j++) {
- if (index_s == s_len)
- break;
- if (index_s % T < numRows) {
- ch[j][i] = s[index_s];
- index_s++;
- } else {
- // 向着右上移动,右上移动时的(x,y)坐标Y正好随着周期变化
- int row_id = numRows - i % T_length - 1;
- ch[row_id][i] = s[index_s];
- index_s++;
- break;
- }
- }
- }
- string ans;
- for (auto c_line : ch) {
- for (auto c : c_line) {
- if (c)
- ans += c;
- }
- }
- return ans;
- }
- };
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |