zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    chrome shortkeys
    五笔xu
    getline()报错解决办法
    PCA程序
    c++矩阵运算库Eigen
    yolo接口
    遇到的编译错误及解决办法
    visual studio command window的使用
    NDK+MSYS2+Android sdk编译opencv源码
    面向对象分析与设计笔记(三)
  • 原文地址:https://www.cnblogs.com/MrSaver/p/5904023.html
Copyright © 2011-2022 走看看