題目:
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
給定兩字串s和t,已知t為s加上一個字元重組而成,找出那個字元
較直觀的解法如下
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
for i in t:
if i not in s:
return i
else:
s=s.replace(i,"",1)
一個一個看t的元素是否在s內
若在則將一個在s內的該元素移除
反之則代表我們找到了多出的那個字元,回傳它
最後執行時間33ms(faster than 95.91%)
也能用位元運算的^來解
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
ans=0
for i in t:
ans=ans^ord(i)
for i in s:
ans=ans^ord(i)
return chr(ans)
設定ans=0
將s,t內所有字元轉為ASCII編碼,和ans行^運算(0^x=x,x^x=0)
運用^的交換律,最後的運算結果即為多出的那個字元的ASCII編碼
將其轉換為字元後回傳
最後執行時間33ms(faster than 95.91%)
那我們下題見