LeetCode By Go

[LeetCode By Go 25]389. Find the

2017-08-18  本文已影响11人  miltonsun

题目

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 {

        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读