[LeetCode] 389. Find the Difference
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
andt
consist of lowercase English letters.
找不同。
给定两个字符串
s
和t
,它们只包含小写字母。字符串
t
由字符串s
随机重排,然后在随机位置添加一个字母。请找出在
t
中被添加的字母。
思路还是用异或 XOR,两边按 char 做 XOR。相同的 char 做 XOR 结果为 0,如果 S 和 T 一模一样,最后的结果会是 0;在 T 中额外的 char 异或 0 的时候,会得到它本身。代码如下,
1 /** 2 * @param {string} s 3 * @param {string} t 4 * @return {character} 5 */ 6 var findTheDifference = function(s, t) { 7 let ss = s.split('').sort(); 8 let tt = t.split('').sort(); 9 let i; 10 for (i = 0; i < ss.length; i++) { 11 if (ss[i] !== tt[i]) { 12 return tt[i]; 13 } 14 } 15 return tt[i]; 16 };
2020年1月2日更新
之前的做法根本不是位运算,而是简单的数组排序一一比较。位运算代码如下
时间O(n) - number of characters
空间O(1)
JavaScript实现
1 /** 2 * @param {string} s 3 * @param {string} t 4 * @return {character} 5 */ 6 var findTheDifference = function (s, t) { 7 let c = t.charCodeAt(t.length - 1); 8 for (let i = 0; i < s.length; i++) { 9 c ^= s.charCodeAt(i); 10 c ^= t.charCodeAt(i); 11 } 12 return String.fromCharCode(c); 13 };
Java实现
1 class Solution { 2 public char findTheDifference(String s, String t) { 3 char c = t.charAt(t.length() - 1); 4 for (int i = 0; i < s.length(); i++) { 5 c ^= s.charAt(i); 6 c ^= t.charAt(i); 7 } 8 return c; 9 } 10 }