美文网首页LeetCode By Go
[LeetCode By Go 25]389. Find the

[LeetCode By Go 25]389. Find the

作者: miltonsun | 来源:发表于2017-08-18 16:10 被阅读11次

    题目

    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 {
    
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 25]389. Find the

        本文链接:https://www.haomeiwen.com/subject/mjuarxtx.html