第十一周leeetcode题

来源:互联网 发布:主题模型 知乎 编辑:程序博客网 时间:2024/05/19 07:07

Description:

iven 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:eExplanation:'e' is the letter that was added.

找两个单词不同的字母。用异或可以快速完成。将要返回的变量re的初始值设为0,依次与两个单词的字母异或。异或的结果与字母的顺序无关,因此,每当有两个相同的字母异或时会得到0,返回的值必为剩余的一个“另类的”字母。代码如下:


class Solution {
public:
    char findTheDifference(string s, string t) {
        int a=s.length();
        int b=t.length();
        char re=0;
        for(int i=0;i<a;i++)
        {
            re^=s[i];
        }
        
        for(int i=0;i<b;i++)
        {
            re^=t[i];
        }
        
        return re;
    }
};

0 0
原创粉丝点击