//LeetCode6. Z 字形变换
class Solution {
public:
string convert(string str, int n) {
int len = str.size();
if (n == 1) return str;
int m = (len / (n + n - 2) + 1) * (n - 1);
vector<string>s(n, string(m, ' '));
int dir = 1;
int x = 0;
int y = 0;
for (int i = 0; i < len; i++) {
s[x][y] = str[i];
switch (dir) {
case 1:
if (x + 1 < n) {
x++;
}
else {
x--;
y++;
dir = 2;
}
break;
case 2:
if (x - 1 >= 0) {
x--;
y++;
}
else {
x++;
dir = 1;
}
break;
}
}
string ans;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (s[i][j] != ' ') ans += s[i][j];
return ans;
}
};
LeetCode6. Z 字形变换
最新推荐文章于 2024-08-20 10:34:34 发布