Skip to content
On this page

389. 找不同

原题链接:LeetCode 389. 找不同

题目描述

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

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

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

示例 1:

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

示例 2:

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

提示:

- `0 <= s.length <= 1000`

- `t.length == s.length + 1`

- `s` 和 `t` 只包含小写字母

难度: Easy


题解代码

javascript
/**
 * @param {string} s
 * @param {string} t
 * @return {character}
 */
// 先排序,然后逐个比较
var findTheDifference = function(s, t) {
  s = s.split('').sort().join('');
  t = t.split('').sort().join('');

  for (let i = 0; i < t.length; i++) {
      if (s[i] != t[i]) {
          return t[i];
      }
  }
};

// 一次遍历计算出两个字符串的ASCII总和,根据差值得出插入的字符
var findTheDifference = function(s, t) {
  if (!s.length) return t;
  let sum1 = 0, sum2 = 0, i = 0;

  while (i < t.length) {
      if (s[i]) sum1 += s.charCodeAt(i);
      if (t[i]) sum2 += t.charCodeAt(i);
      i++;
  }
  return String.fromCharCode(sum2 - sum1);
}

// 通过转化为数组, 通过 indexOf 进行遍历,通过splice删除
// 剩下的元素通过 toString()转化得到
var findTheDifference = function(s, t) {
  let a = s.split('')
  let b = t.split('')
  for(let i = 0; i < a.length; i++){
      let tmp = 0
      tmp = b.indexOf(a[i])
      b.splice(tmp,1)
  }
  return b.toString()
}
// TODO: 异或处理

技术文档集合