题目描述:
LeetCode 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.
题目大意:
给定两个字符串s和t,都只包含小写字母。
字符串t由字符串s打乱顺序并且额外在随机位置添加一个字母组成。
寻找t中新增的那个字母。
测试用例如题目描述。
解题思路:
分别统计s与t的字母个数,然后比对即可。若使用Python解题,可以使用collections.Dict。
Python代码:
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
ds = collections.Counter(s)
dt = collections.Counter(t)
return (dt - ds).keys().pop()