389. Find the Difference

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、t 比 s只多一个字符,其他都一样;
2、采用bitmap来记录每个字符出现的次数,不相等的那个就肯定是要找的。

代码(C)

int Index(char x)
{
    return x - 'a';
}

char findTheDifference(char* s, char* t) {
    int bit_map_s[26] = {0};
    int bit_map_t[26] = {0};
    int len_s = strlen(s);
    for (int i = 0; i < len_s; i++)
    {
        bit_map_s[Index(s[i])]++;
        bit_map_t[Index(t[i])]++;
    }
    bit_map_t[Index(t[len_s])]++;

    char res;
    for (int i = 0; i < 26; i++)
    {
        if (bit_map_s[i] != bit_map_t[i])
        {
            res = 'a' + i;   
            break;
        }
    }
    return res;
}

代码(python)

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        dic_s = collections.Counter(s)
        dic_t = collections.Counter(t)
        return (dic_t - dic_s).keys().pop()

学习总结
1、C语言代码没什么好说的
2、关于pyhton的代码,主要就是两点:dic的使用,内建模块collections的使用。
Counter可以理解为就是一个简单的计数器
class collections.Counter([iterable-or-mapping])
计数器是dict子类的计数 hashable 对象。它是一个无序的集合,其中他们计数存储作为字典值和元素存储为字典键。计数允许为任何整数值,包括零或负计数。计数器类是类似于袋或在其他语言中的多重集。这里

collections.Counter(s):得到每个字符和其出现次数的字典,如{‘g’: 2, ‘m’: 2, ‘r’: 2, ‘a’: 1, ‘i’: 1, ‘o’: 1, ‘n’: 1, ‘p’: 1}
dic_t - dic_s: 得到差集,那就只有多出的那一个字符了,如[‘e’, 1]
(dic_t - dic_s).keys(): 得到字符 ‘e’

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值