【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);
}
相关推荐
nujnewnehc1 小时前
ps, ai, ae插件都可以用html和js开发了
前端·javascript
孤飞4 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
Jagger_4 小时前
整洁架构三连问:是什么,怎么做,为什么要用
前端
一个处女座的程序猿O(∩_∩)O5 小时前
React 完全入门指南:从基础概念到组件协作
前端·react.js·前端框架
技术专家5 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
前端摸鱼匠5 小时前
Vue 3 的defineEmits编译器宏:详解<script setup>中defineEmits的使用
前端·javascript·vue.js·前端框架·ecmascript
csdn_aspnet5 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
里欧跑得慢5 小时前
Flutter 测试全攻略:从单元测试到集成测试的完整实践
前端·css·flutter·web
Jagger_5 小时前
前端整洁架构详解
前端
鹿角片ljp5 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展