日期:2026年2月7日
ZeroJudge 題目連結:c045. 00490 - Rotating Sentences
解題想法
這題我在 Python 是用二維串列儲存字串內容,在 C++ 則是用 vector 加 string 儲存內容。先讀取所有的測資,接下來用二層 for 迴圈讀取測資中的字元,外層處理欄位,內容從最後一列讀取到第 0 列。輸出答案時,如果這一列不是整整空白才要輸出。
Python 程式碼
使用時間約為 26 ms,記憶體約為 3.4 MB,通過測試。
import sys
lines = sys.stdin.readlines() # 一次讀取所有的資測,包含結尾的 \n
n = len(lines) # 共有 n 列
ans = [[] for _ in range(100)] # 答案,題目限制每列最多 100 個字元
for c in range(100): # 欄位,題目限制每列最多 100 個字元
for r in range(n-1, -1, -1): # 依序讀取第 n-1 到 0 列
m = len(lines[r]) - 1
if c < m: ans[c].append(lines[r][c]) # 如果 r 沒有出界,lines[r][c] 加入 ans[c]
else: ans[c].append(" ") # 反之,空格加入 ans[c]
for a in ans: # 依序讀取 ans 每一列的資料 a
row = "".join(a) # 將 a 組成字串 row
if not row.isspace(): # 如果 row 不是整列空白
sys.stdout.write(row + "\n")
C++ 程式碼
使用時間約為 2 ms,記憶體約為 356 kB,通過測試。
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
vector<string> lines; // 所有的測資
string line;
while(getline(cin, line)) lines.push_back(line);
int n = (int)lines.size(); // 共有 n 列
vector<string> ans (100); // 答案,題目限制每列最多 100 個字元
for(int c=0; c<100; c++) { // 欄位,題目限制每列最多 100 個字元
for(int r=n-1; r>=0; r--) { // 依序讀取第 n-1 到 0 列
int m = (int)lines[r].size();
if (c < m) ans[c] += lines[r][c]; // 如果 r 沒有出界,lines[r][c] 加入 ans[c]
else ans[c] += ' '; // 反之,空格加入 ans[c]
}
}
for(string a : ans) { // 依序讀取 ans 每一列的資料 a
bool allspace = true; // 檢查 a 是否整列空白
for(char ch : a) {
if (!isspace(ch)) {
allspace = false;
break;
}
}
if (!allspace) cout << a << "\n"; // 如果 a 不是整列空白,印出 a
}
return 0;
}
沒有留言:
張貼留言