日期:2025年3月30日
ZeroJudge 題目連結:h033. 雜訊移除 (Noise)
解題想法
這題在 Python 可以用 replace 將不要的字元取代成空字串。
Python 程式碼
用 replace 可以取代字串中指定的字元,取代為空字串就可以移除特定字元。使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
import sys
def is_palindrome(s): # 檢查 s 是否為迴文字串
n = len(s) # s 的長度 n
for i in range(n//2): # 依序檢查從頭尾兩端往中間檢查
if s[i] != s[n-i-1]: return False # 如果字元不相同回傳 False
return True # 如果可以跑完 for loop,回傳 True
for line in sys.stdin:
s, n = line.split() # 要分析的字串 s,要移除的字元 n
s = s.replace(n, "") # 將 s 之中的 n 取代為空字串
print("Yes" if is_palindrome(s) else "No") # 印出答案
如果不使用 replace,也可以遍歷字串,將要留下來的字元存到另一個空字串裡。使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
import sys
def is_palindrome(s): # 檢查 s 是否為迴文字串
n = len(s) # s 的長度 n
for i in range(n//2): # 依序檢查從頭尾兩端往中間檢查
if s[i] != s[n-i-1]: return False # 如果字元不相同回傳 False
return True # 如果可以跑完 for loop,回傳 True
for line in sys.stdin:
s, n = line.split() # 要分析的字串 s,要移除的字元 n
t = "" # 儲存 s 移除 n 之後的空字串
for c in s: # 依序由 s 讀取字元 c
if c != n: t += c # 如果 c 不等於 n,接到 t 之後
print("Yes" if is_palindrome(t) else "No") # 印出答案