[leetcode] 389. Find the Difference

来源:互联网 发布:连续统假设知乎 编辑:程序博客网 时间:2024/06/16 02:06

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.

Example:

Input:s = "abcd"t = "abcde"Output:eExplanation:'e' is the letter that was added.

这道题是找字符串中多出的字符,题目难度为Easy。

可以统计字符串s中各字符出现的次数,然后遍历字符串t,逐个比对其中字符,最终单独剩下的字符即是多出的字符。具体代码:

class Solution {public:    char findTheDifference(string s, string t) {        vector<int> cnt(26, 0);        for(auto c:s) ++cnt[c-'a'];        for(auto c:t) --cnt[c-'a'];        for(int i=0; i<26; ++i) {            if(cnt[i]) return 'a' + i;        }    }};

还可以通过位操作来找多出的字符,任意字符按位异或自己得0,所以把s和t中所有字符逐个按位异或即可得出多出的字符。具体代码:

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

0 0
原创粉丝点击