给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 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 只包含小写字母
我的代码:
func findTheDifference(s string, t string) byte {
r := [26]int{}
for _, v := range s{
r[v - 'a']++
}
for _, v := range t{
r[v - 'a']--
}
for i, v := range r{
if v == -1{
return (byte)('a' + i)
}
}
return 0
}
官方题解:
方法一:计数
首先遍历字符串 ss,对其中的每个字符都将计数值加 11;然后遍历字符串 tt,对其中的每个字符都将计数值减 11。当发现某个字符计数值为负数时,说明该字符在字符串 tt 中出现的次数大于在字符串 ss 中出现的次数,因此该字符为被添加的字符。
func findTheDifference(s, t string) byte {
cnt := [26]int{}
for _, ch := range s {
cnt[ch-'a']++
}
for i := 0; ; i++ {
ch := t[i]
cnt[ch-'a']--
if cnt[ch-'a'] < 0 {
return ch
}
}
}
func findTheDifference(s, t string) byte {
sum := 0
for _, ch := range s {
sum -= int(ch)
}
for _, ch := range t {
sum += int(ch)
}
return byte(sum)
}
方法三:位运算
如果将两个字符串拼接成一个字符串,则问题转换成求字符串中出现奇数次的字符。类似于「136. 只出现一次的数字」,我们使用位运算的技巧解决本题。
func findTheDifference(s, t string) (diff byte) {
for i := range s {
diff ^= s[i] ^ t[i]
}
return diff ^ t[len(t)-1]
}
//diff默认值为0,0异或任何数(如A),结果还是A