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:
1 2 3
Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added.
Example 2:
1 2
Input: s = "", t = "y" Output: "y"
哈希表:
时间复杂度:O(n)
空间复杂度:O(S),S表示字符集大小。
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: charfindTheDifference(string s, string t){ unordered_map<char,int> set; for (char ch : s)set[ch]++; for (char ch : t) { if (set[ch])set[ch]--; elsereturn ch; } return' '; } };
求和:
时间复杂度:O(n)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: charfindTheDifference(string s, string t){ int as = 0, at = 0; for (char ch: s) { as += ch; } for (char ch: t) { at += ch; } return at - as; } };
位运算:
时间复杂度:O(n)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: charfindTheDifference(string s, string t){ int ret = 0; for (char ch: s) { ret ^= ch; } for (char ch: t) { ret ^= ch; } return ret; } };