【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);
}
相关推荐
梦梦代码精8 分钟前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
XinZong14 分钟前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端
Le_ee40 分钟前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
爱上好庆祝1 小时前
学习js的第七天(wed APIs的开始)
前端·javascript·css·学习·html·css3
Zephyr_01 小时前
Leedcode算法题
java·算法
流年如夢1 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
KaMeidebaby2 小时前
卡梅德生物技术快报|冻干工艺开发:注射用心肌肽全流程参数优化与工程化方案
前端·其他·百度·新浪微博
ooseabiscuit2 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
哆啦A梦15882 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3