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

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

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

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

示例 1:

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

示例 2:

复制代码
输入:s = "", t = "y"
输出:"y"

排序 + 比较

TypeScript 复制代码
// 排序 + 比较
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 "";
}

异或

TypeScript 复制代码
// 异或( 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);
}
相关推荐
Penge666几秒前
JavaScript:BOM 详解
前端
Penge66633 分钟前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge66637 分钟前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge6661 小时前
Sass 了解
前端
Penge6661 小时前
Webpack 打包从 0 到 1 实战笔记
前端
I_belong_to_jesus1 小时前
C++关于分支预测的优化1
开发语言·c++·算法
Penge6661 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge6662 小时前
Ant Design(Antd)了解
前端
wangruofeng2 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github
Penge6662 小时前
JavaScript 核心语法速通
前端