首页 > 编程语言 > 详细

Leecode刷题之旅-C语言/python-389 找不同

时间:2019-03-20 12:45:48      阅读:190      评论:0      收藏:0      [点我收藏+]
/*
 * @lc app=leetcode.cn id=389 lang=c
 *
 * [389] 找不同
 *
 * https://leetcode-cn.com/problems/find-the-difference/description/
 *
 * algorithms
 * Easy (54.68%)
 * Total Accepted:    7.1K
 * Total Submissions: 12.9K
 * Testcase Example:  ‘"abcd"\n"abcde"‘
 *
 * 给定两个字符串 s 和 t,它们只包含小写字母。
 * 
 * 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
 * 
 * 请找出在 t 中被添加的字母。
 * 
 * 
 * 
 * 示例:
 * 
 * 输入:
 * s = "abcd"
 * t = "abcde"
 * 输出:
 * e
 * 
 * 解释:
 * ‘e‘ 是那个被添加的字母。
 * 
 * 
 */
char findTheDifference(char* s, char* t) {
  int len=strlen(s);
    
    int result=(int)t[0];
    for(int i=0;i<len;i++){
        result^=s[i];
        result^=t[i+1];
    }
    return (char)result;
}

相同的数异或为0,而俩数组只有一个字母不同,所以只要全都异或一遍就只剩下那个不同的字母的ascuii码,ascuii码是int类型,只要强制类型转换为char就行了。

#
# @lc app=leetcode.cn id=389 lang=python3
#
# [389] 找不同
#
# https://leetcode-cn.com/problems/find-the-difference/description/
#
# algorithms
# Easy (54.68%)
# Total Accepted:    7.1K
# Total Submissions: 12.9K
# Testcase Example:  ‘"abcd"\n"abcde"‘
#
# 给定两个字符串 s 和 t,它们只包含小写字母。
# 
# 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
# 
# 请找出在 t 中被添加的字母。
# 
# 
# 
# 示例:
# 
# 输入:
# s = "abcd"
# t = "abcde"
# 
# 输出:
# e
# 
# 解释:
# ‘e‘ 是那个被添加的字母。
# 
# 
#
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        ch=0
        for c in s+t:
            ch^=ord(c)
        return chr(ch)

 

Leecode刷题之旅-C语言/python-389 找不同

原文:https://www.cnblogs.com/lixiaoyao123/p/10564108.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!