【Leetcode 389 】 找不同 —— 位运算

45 阅读1分钟

给定两个字符串 s 和 t ,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例 1:

输入: s = "abcd", t = "abcde"
输出: "e"
解释: 'e' 是那个被添加的字母。

示例 2:

输入: s = "", t = "y"
输出: "y"

 排序 + 比较

// 排序 + 比较
function findTheDifference(s: string, t: string): string {
  const sList = [...s].sort();
  const tList = [...t].sort();
  for (let i = 0; i < tList.length; i++) {
    const v = tList[i];
    if (sList[i] !== v) {
      return v;
    }
  }
  return "";
}

异或 

// 异或( x ^ x = 0) 两个相同的会互相抵消
function findTheDifference2(s: string, t: string): string {
  let res = 0;
  for (const v of s) {
    res ^= v.charCodeAt(0);
  }
  for (const v of t) {
    res ^= v.charCodeAt(0);
  }

  return String.fromCharCode(res);
}