2023年7月1日 星期六

7/2 每日一題(兩組字串中取不同值)

 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.

 

Example 1:

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y"
Output: "y"

 

Constraints:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lowercase English letters.


class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        freq={}
        for i in t:
            freq[i]=freq.get(i,0)+1
            #避免KeyError,當Key不存在時 新增{key:0}
        for i in s:
            freq[i] -=1 #當循環結束 val==1的值 就是不同的key
        for key,val in freq.items():
            if val > 0:
                return key
-------------------------------法二
from collections import Counter
s='abcd'
t='abdcy'
c_s=Counter(s)
c_t=Counter(t)
print(c_s)
print(c_t)
print(c_t-c_s)


---------------------終端機
Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1}) Counter({'a': 1, 'b': 1, 'd': 1, 'c': 1, 'y': 1}) Counter({'y': 1})






























































標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁