LeetCode.389 找不同

164 阅读1分钟

这是我参与8月更文挑战的第26天,活动详情查看:8月更文挑战

题目描述:

389. 找不同 - 力扣(LeetCode) (leetcode-cn.com)

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

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

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

示例 1:

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

示例 2:

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

示例 3:

输入:s = "a", t = "aa"
输出:"a"

示例 4:

输入:s = "ae", t = "aea"
输出:"a"

提示:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • st 只包含小写字母

思路分析

计数法

首先遍历字符串 s,统计其中每个字符的个数

然后遍历字符串 t,对其中的每个字符都将计数值减 1

当发现某个字符计数值为负数时,说明该字符在字符串 t 中出现的次数大于在字符串 s 中出现的次数

AC代码

class Solution {
    fun findTheDifference(s: String, t: String): Char {
        if (s == "") return t.toCharArray()[0]
        val arr = IntArray(26)
        for (c in s) {
            val key = (c - 97).toInt()
            arr[key] += -1
        }
        for (c in t) {
            val key = (c - 97).toInt()
            arr[key] += 1
        }
        arr.forEachIndexed { index, i ->
            if (i == 1) {
                return (index + 97).toChar()
            }
        }
        return ' '
    }
}

利用kotlin的高阶语法,但是执行时间变长了,有得有失。

class Solution {
    fun findTheDifference(s: String, t: String): Char {
        val arr = IntArray(26)
        s.forEach { arr[it - 'a']++ }
        t.forEach { if (--arr[it - 'a'] < 0) return it }
        return ' '
    }
}

求和

将字符串 s 中每个字符的 ASCII 码的值求和,得到 ss 对字符串 tt 同样的方法得到 tt 两者的差值 tt - ss 对应的字符即为答案

AC代码

class Solution {
    fun findTheDifference(s: String, t: String): Char {
        var ss = 0
        var tt = 0
        val arr = IntArray(26)
        for (c in s) {
            ss += c.toInt()
        }
        for (c in t) {
            tt += c.toInt()
        }
        
        return (tt - ss).toChar()
    }
}

异或

异或的原理我们在LeetCode.136 只出现一次的数字说的解释的很清楚,这里就不再赘述了。

 class Solution {
     fun findTheDifference(s: String, t: String): Char =
        (s + t).chars().reduce { left, right -> left xor right }.asInt.toChar()
}

总结

前两种都是常规解法,位运算目前做的题还不多,还没有形成惯性思维,不看题解还是想不到这解法。

参考

找不同 - 找不同 - 力扣(LeetCode) (leetcode-cn.com)

Kotlin的几种解法 - 找不同 - 力扣(LeetCode) (leetcode-cn.com)

389. 找不同 - 找不同 - 力扣(LeetCode) (leetcode-cn.com)