관리 메뉴

솜씨좋은장씨

[leetCode] 389. Find the Difference (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 389. Find the Difference (Python)

솜씨좋은장씨 2021. 2. 3. 22:09
728x90
반응형

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"

Example 3:

Input: s = "a", t = "aa"
Output: "a"

Example 4:

Input: s = "ae", t = "aea"
Output: "a"

Constraints:

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

Solution

from collections import Counter

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:   
        cnt_s = Counter(list(s))
        cnt_t = Counter(list(t))
        
        s_keys = list(cnt_s.keys())
        
        for key in s_keys:
            cnt_t[key] = cnt_t[key] - cnt_s[key]
            
        t_items = [item[0] for item in cnt_t.items() if item[1] != 0]
        
        answer = "".join(t_items)      
        
            
        return answer

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments