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’