美文网首页
[LeetCode]389. Find the Differen

[LeetCode]389. Find the Differen

作者: Eazow | 来源:发表于2017-05-26 16:58 被阅读56次
题目

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.
难度

Easy

方法

字符串t是字符串s中的字符打乱后生成的,为了找出t中不同的字符,可以采用异或的方法

python代码
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        i = 0
        difference = 0
        for i in xrange(len(s)):
            difference ^= ord(s[i]) ^ ord(t[i])

        return chr(difference ^ ord(t[-1]))

assert Solution().findTheDifference("abcd", "abcde") == "e"
assert Solution().findTheDifference("abcd", "dceba") == "e"

相关文章

网友评论

      本文标题:[LeetCode]389. Find the Differen

      本文链接:https://www.haomeiwen.com/subject/smexfxtx.html