Skip to content

LeetCode: 389-Find the Difference 解題紀錄

Last Updated on 2022-02-07 by Clay

題目

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.

題目給定兩個字串,第一組是原始的字串,第二組可能是隨機洗牌後隨機加入一個新的字元的字串。我們要找出那個多出來的字元,並且返回。


解題思路

解題的思路非常單純,因為每個字元都可以視為一個 ASCII 的數值,只要計算出兩個字串的數值差,就可以得知哪個字元是多出來的了。


複雜度

Time ComplexityO(n)
Space ComplexityO(1)


C++ 範例程式碼

class Solution {
public:
    char findTheDifference(string s, string t) {
        int addChar = 0;
        
        for (int i=0; i<s.size(); ++i) {
            addChar += t[i] - s[i];
        }
        
        addChar += t.back();
        
        return char(addChar);
    }
};



Python 範例程式碼

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        n = 0
        
        for i in range(len(s)):
            n += ord(t[i]) - ord(s[i])
        
        n += ord(t[-1])
                
        return chr(n)

References


Read More

Leave a Reply