Leetcode389. 找不同

题目

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例:

输入:
s = "abcd"
t = "abcde"

输出:
e

解释:
'e' 是那个被添加的字母。

C++解法

方法一:用字典统计s和t每个字符出现的次数。

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;
class Solution {
public:
    char findTheDifference(string s, string t) {
        map<char, int> scounter, tcounter;
        for (auto c: s) ++scounter[c];
        for (auto c: t) ++tcounter[c];
        for (auto item: tcounter) {
            if (tcounter[item.first] != scounter[item.first]) return item.first;
        }
        return -1;
    }
};
int main(int argc, const char * argv[]) {
    Solution solution;
    cout << solution.findTheDifference("abcd", "abcde") << endl;
    return 0;
}

方法二:
由于s和t只有一个字符的差别,用异或操作可以把这个字符还原出来。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。...
    鬼鬼812阅读 285评论 1 3
  • 题目来源:https://leetcode-cn.com/problems/find-the-difference...
    80e038d7cdfb阅读 262评论 0 0
  • 找不同 题目 给定两个字符串 s 和 t,它们只包含小写字母。 字符串t由字符串s随机重排,然后在随机位置添加一个...
    饮酒醉回忆阅读 248评论 0 1
  • 给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请...
    0error_阅读 264评论 0 0
  • 虽然大部分人不是天才,但是遵循着天才的思考策略,我们也可以更好得使用我们的脑子,快速学习,做出明智的选择。 9条定...
    Renatayaaaa阅读 354评论 0 0

友情链接更多精彩内容