字符串自動校對(修正拼寫錯誤字符串)
題目描述:(1)三個同樣的字母連在一起,一定是拼寫錯誤,去掉一個就好了,比如:helllo->hello;(2)兩對一樣的字母(AABB型)連在一起,一定是拼寫錯誤,去掉第二對的一個字母就好了:比如:helloo->hello;(3)上面的規則優先“從左到右匹配”,即如果是AABBCC,雖然AABB和BBCC都是錯誤拼寫,應該優先考慮修復AABB,結果爲AABCC
輸入描述:第一行包括一個數字N,表示本次用例包括多少個待校驗的字符串。後面跟隨N行,每行爲一個待校驗的字符串。
輸出描述:N行,每行包括一個被修復後的字符串。
舉例:
輸入:2
helloo
wooooooow
輸出:hello
woow
代碼實現:
#字符串修正函數
def correction_string(s):
n = len(s)
r = list(s[:min(len(s), 2)])
for i in range(2, n):
if s[i] == r[-1] == r[-2]:
continue
if s[i] == r[-1] and len(r) > 2 and r[-2] == r[-3]:
continue
r.append(s[i])
new_string = ''.join(r)
return new_string
for i in range(int(input())):
s=input()
print(correction_string(s))
運行結果: