389. Find the Difference Add to List(新添字符)

本文介绍了通过四种不同算法找出在一个字符串中新增加的一个字母的方法。包括使用布尔数组标记、哈希表计数对比、按位异或运算及加减法实现。这些算法简单实用,适合初学者学习。

DescriptionSubmissionsSolutions
Total Accepted: 60224
Total Submissions: 117313
Difficulty: Easy
Contributor: LeetCode
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:
e

Explanation:
‘e’ is the letter that was added.

以前有个字符串,再给一个新的字符串,看新加的是哪一个

解法1:

class Solution {
public:
    char findTheDifference(string s, string t) {

    bool hap[26] ={ true};
    for (int i = 0; i < t.size(); i++)
    {
        hap[t[i] - 'A' - 32]=false;
    }
    for (int i = 0; i < s.size(); i++)
    {
        hap[s[i] - 'A'-32]=true;
    }

    for (int i = 0; i < 26; i++)
    {
        if (hap[i] == false)
        {
        return char(i + 'A' + 32) ;
        }
    }
    }
};
//很稳健的超时了,下面是大神的

解法2:

class Solution {
public:
    char findTheDifference(string s, string t) {
    unordered_map<char, int>a;//当然建立哈希表啊,老哥,char是索引类型,int为元素类型
    for (char b : s)//遍历短的字符串
    {
        a[b]++;
    }
    for (char b : t)
    {
        if( --a[b]<0)//多余的那个自然就多减了
        {
            cout << b;//
        }
    }
    }
解法3:
//运用按位异或解决:   a*a=0;并且符合交换律
class Solution {
public:
    char findTheDifference(string s, string t) {
    char res=0;
    for(char a:s)
    {
        res^=a;
    }
    for(char b:t)
    {
        res^=b;
    }
    return res;

    }
加减法.............
class Solution {
public:
    char findTheDifference(string s, string t) {
    char res = 0;
        for (char c : s) res -= c;
        for (char c : t) res += c;
       return res;
    }
};
解法4:
class Solution {
public:
    char findTheDifference(string s, string t) {
        return accumulate(begin(s), end(s += t), 0, bit_xor<int>());
    }
};

参考链接:
http://www.cnblogs.com/grandyang/p/5816418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值