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

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

字符串 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);
}
相关推荐
gskyi1 天前
uni-app 高阶实战:onLoad与getCurrentPages深度技巧
前端·javascript·vue.js·uni-app
月明水寒1 天前
IDEA2026.1 vue文件报错
前端·javascript·vue.js·intellij-idea·idea·intellij idea
IpdataCloud1 天前
不同业务如何选IP查询更新频率?离线与在线协同策略
前端·网络协议·tcp/ip·html
牛奶1 天前
不经过服务器,两个人怎么直接通话?
前端·websocket·webrtc
啦啦啦_99991 天前
2. KNN算法之 分类&回归API实现
算法
神探小白牙1 天前
3D饼图,带背景图和自定义图例(threejs)
开发语言·前端·javascript·3d·vue
X journey1 天前
机器学习进阶(23):K-means聚类
人工智能·算法·机器学习
IT_陈寒1 天前
SpringBoot自动配置的坑差点没把我埋了
前端·人工智能·后端
光影少年1 天前
高级前端需要学习那些东西?
前端·人工智能·学习·aigc·ai编程
mjhcsp1 天前
根号快速计算牛顿迭代法
开发语言·c++·算法·迭代法