Z 字形变换
题目要求:将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
今天的题目是一道模拟题,直接对目标情况进行模拟即可,虽然是两层循环嵌套,但是实际时间复杂度为O(n)。代码如下:
#include <cstdio> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; string convert(string s, int numRows); int main() { string s; cin >> s; int num; cin >> num; cout << convert(s,num); return 0; } string convert(string s, int numRows) { if (numRows == 1) return s; string ans = s; int len = s.length(); int index = 0; for (int j = 0; j < numRows; ++j) { int i = 0; while( i < (len / (numRows * 2 - 2) + 1) && (i * (numRows * 2 - 2) + j) < len) { if (j == 0 || j == numRows - 1) { ans[index] = s[i * (numRows * 2 - 2) + j]; index++; } else { ans[index] = s[i * (numRows * 2 - 2) + j]; index++; if(((i + 1) * (numRows * 2 - 2) - j) < len) { ans[index] = s[(i + 1) * (numRows * 2 - 2) - j]; index++; } } ++i; } } return ans; }