日期:2026年1月24日
ZeroJudge 題目連結:c007. 00272 - TeX Quotes
解題想法
讀取一行測資,再依序讀取這行的每個字元並記錄讀到 " 的次數 left,讀到第 1 個 " 時將 left 設定成 1,在要輸出的字串中加上 ``;如果讀到 " 時 left 等於 1,代表這是第 2 個 ",將 left 歸零,在要輸出的字串中加上 '';如果是其它字串則直接加到要輸出的字串後面。
Python 程式碼
使用時間約為 9 ms,記憶體約為 3.1 MB,通過測試。
import sys
left = 0
result = []
lines = sys.stdin.readlines()
for line in lines:
s = []
for c in line.rstrip():
if c == "\"":
if left == 0:
s += ["`", "`"]
left = 1
else:
s += ["\'", "\'"]
left = 0
else: s.append(c)
res = "".join(s)
result.append(f"{res}\n")
sys.stdout.write("".join(result))
C++ 程式碼
使用時間約為 1 ms,記憶體約為 324 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int left = 0;
string s, t;
while(getline(cin, t)) {
s.clear();
for(char c : t) {
if (c == '\"') {
if (left == 0) {
s += "``";
left = 1;
} else {
s += "\'\'";
left = 0;
}
} else {
s += c;
}
}
cout << s << "\n";
}
return 0;
}
沒有留言:
張貼留言