leetcode - 389. Find the Difference

Description

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.

Solution

Dict

Use a dict to compare s and t

Bit Manipulation

If the character appears both in s and t, then it must appear multipliers of 2. So we could use xor.

Time complexity: o ( m + n ) o(m+n) o(m+n). where m and n are lengths of s and t
Space complexity: o ( 1 ) o(1) o(1)

Code

Dict

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        chars = {}
        for ch in s:
            chars[ch] = chars.get(ch, 0) + 1
        for ch in t:
            if ch not in chars:
                return ch
            chars[ch] -= 1
            if chars[ch] == 0:
                chars.pop(ch)
        return list(chars.keys())[0]

Bit Manipulation

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        res = 0
        for ch in s:
            res ^= ord(ch)
        for ch in t:
            res ^= ord(ch)
        return chr(res)

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)