码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Find the Difference_389

时间:2016-09-24 21:47:09      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

LeetCode:Find the Difference_389

标签:

原文地址:http://www.cnblogs.com/MrSaver/p/5904023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!