zoukankan      html  css  js  c++  java
  • 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
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    《民工》随笔
    最近繁忙,暂停更新
    UVA 839 Not so Mobile
    UVA 310 Lsystem
    UVA 10602 Editor Nottoobad
    UVA 10562 Undraw the Trees
    UVA 327 Evaluating Simple C Expressions
    UVA 10954 Add All
    UVA 270 Lining Up
    UVA 699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9969377.html
Copyright © 2011-2022 走看看