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.

 

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 ago Accepted 28 ms python
2 minutes ago Accepted 5 ms java
6 minutes ago Accepted 4 ms cpp

 

posted @ 2018-11-16 15:03  Veritas_des_Liberty  阅读(170)  评论(0编辑  收藏  举报