Leetcode 由易入难 389. Find the Difference

来源:互联网 发布:精雕软件视频教程 编辑:程序博客网 时间:2024/05/28 15:56

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.

由于一个字符只出现一次而且其它字符都出现了偶数次。用搜索来做就没必要了,利用异或运算的两个特性——1.自己与自己异或结果为0。2.异或满足交换律。
这题主要考验这个性质。

java实现

public char findTheDifference(String s, String t) {    char c = 0;    for (int i = 0; i < s.length(); ++i) {        c ^= s.charAt(i);    }    for (int i = 0; i < t.length(); ++i) {        c ^= t.charAt(i);    }    return c;}

c++实现

class Solution {public:    char findTheDifference(string s, string t) {        char r=0;        for(char c:s) r ^=c;        for(char c:t) r ^=c;        return r;    }};

注意这里的char c:s 此语句含义是相当于 int i;i