/* * @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" "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" "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)