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

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"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,501评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,956评论 0 0
  • A我今天学了什么 1css背景 1.2文本 1.3css字体 1.4css链接 1.5 列表样式(针对ul) 1...
    Rosemarry丶阅读 2,394评论 0 0
  • 一、概念: 1.鲶鱼效应:被对手激活的现象,被称为“鲶鱼效应”,这是一种用危机、竞争、假想敌的方式,激活团队士气,...
    Sunflower1992阅读 2,795评论 0 0
  • 原来你也在这里(刘若英) 点此欣赏 这是真的。 有个村庄的小康之家的女孩子,生得美,有许多人来做媒,但都没有说成。...
    袁卫星阅读 5,807评论 2 4

友情链接更多精彩内容