題目要求:將一個給定字串根據給定的行數,以從上往下、從左到右進行 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; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/40806.html
標籤:C++
上一篇:最長回文子串
