LeetCode:Find the Difference_389

LeetCode:Find the Difference

【问题再现】

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.

【优质算法】

    public char findTheDifference(String s, String t) {
        char[] sArray = s.toCharArray();
        char[] tArray = t.toCharArray();
        char t1 = 0;
        for(char c1:sArray)
            t1^=c1;
        for(char c2:tArray)
            t1^=c2;
        return(char)t1;
    }

【题后反思】

  对异或运算符^的理解:

异或运算符是用符号“^”表示的,其运算规律是:

   两个操作数的位中,相同则结果为0,不同则结果为1 。

  一个重要的运算性质:

     A^B^B=A;

  该题运用了异或的运算规律和性质,算法可以这么理解,将两条字符串异或在一起 ,即(0^a^b^c^d)^(a^b^c^d^e )其中相同的都异或为0了,剩下的就是那一个被添加的字符。

  括号分别表示两条字符串,其中第二条比第一条多了一个e.

 

posted @ 2016-09-24 20:33  子烁爱学习  阅读(219)  评论(0编辑  收藏  举报