题目
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
解题思路
使用异或的原理
a ^ 0 = a
a ^ a = 0
a ^ b ^ c = a ^ ( b ^ c )
因此,将s,t两个字符串的所有字符转为byte类型进行异或,最后的结果就是多出来的字符
代码
findTheDifference.go
package _389_Find_the_Difference
func FindTheDifference(s string, t string) byte {
var ret byte
for _, v := range s {
ret = ret ^ byte(v)
}
for _, v := range t {
ret = ret ^ byte(v)
}
return ret
}
测试
findTheDifference_test.go
package _389_Find_the_Difference
import "testing"
func TestFindTheDifference(t *testing.T) {
var tests = []struct{
s string
t string
output byte
}{
{"abcd","abcde", byte('e')},
}
for _, test := range tests {
ret := FindTheDifference(test.s, test.t)
if ret == test.output {
}
}
}