389. Find the Difference

本文介绍了三种不同的编程方法来解决一个特定的问题:给定两个由小写字母组成的字符串s和t,其中t是由s随机打乱并添加了一个随机字符生成的。目标是找出这个被添加的字符。文章提供了C++、Java和Python的解决方案,并展示了每种方法的时间效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

Approach #1: C++.

class Solution {
public:
    char findTheDifference(string s, string t) {
        unordered_map<char, int> mp;
        for (int i = 0; i < t.length(); ++i)
            mp[t[i]]++;
        for (int i = 0; i < s.length(); ++i)
            mp[s[i]]--;
        for (int i = 0; i < t.length(); ++i)
            if (mp[t[i]] == 1) return t[i];
        
    }
};

  

Approach #2: Java.

class Solution {
    public char findTheDifference(String s, String t) {
        int n = t.length();
        char c = t.charAt(n-1);
        for (int i = 0; i < n-1; ++i) {
            c ^= s.charAt(i);
            c ^= t.charAt(i);
        }
        return c;
    }
}

  

Approach #3: Python.

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        s, t = sorted(s), sorted(t)
        return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0]
    

  

Time SubmittedStatusRuntimeLanguage
a few seconds agoAccepted28 mspython
2 minutes agoAccepted5 msjava
6 minutes agoAccepted4 mscpp

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/9969377.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值