zoukankan      html  css  js  c++  java
  • Leecode刷题之旅-C语言/python-389 找不同

    /*
     * @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)
  • 相关阅读:
    jsp 生成静态页面
    flash cs5
    sql 设置主键
    sql 分页查询
    java 获取系统时间
    android 源码 编译
    android 退出 activity
    广告平台
    android 引擎
    maya 花草 制作动画
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10564108.html
Copyright © 2011-2022 走看看