Last Updated on 2022-02-07 by Clay
題目
You are given two stringss
andt
. Stringt
is generated by random shuffling strings
and then add one more letter at a random position. Return the letter that was added tot
.
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
andt
consist of lowercase English letters.
題目給定兩個字串,第一組是原始的字串,第二組可能是隨機洗牌後隨機加入一個新的字元的字串。我們要找出那個多出來的字元,並且返回。
解題思路
解題的思路非常單純,因為每個字元都可以視為一個 ASCII 的數值,只要計算出兩個字串的數值差,就可以得知哪個字元是多出來的了。
複雜度
Time Complexity | O(n) |
Space Complexity | O(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)