zoukankan      html  css  js  c++  java
  • [LeetCode] 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.
    

     找出两个字符串中不同的字母,且这个不同的字母只出现了一次,其他的字母出现了2次。利用XOR即可求解。

    class Solution {
    public:
        char findTheDifference(string s, string t) {
            char res = 0;
            for (char c : s)
                res ^= c;
            for (char c : t)
                res ^= c;
            return res;
        }
    };
    // 3 ms

    因为题目中是2个字符串,故可以分别对两个字符串中的字母求和,再用这两个总和相减,得到的差即是所求的那个字母。

    class Solution {
    public:
        char findTheDifference(string s, string t) {
            int sum_s = 0, sum_t = 0;
            for (auto c : s)
                sum_s += c;
            for (auto c : t)
                sum_t += c;
            return sum_t - sum_s;
        }
    };
    // 3 ms

    利用map存储s中字母出现的次数。形成一个查找表。使用t中字母查找,找不到的就是所求的那个字母。

    class Solution {
    public:
        char findTheDifference(string s, string t) {
            unordered_map<char, int> m;
            for (int i = 0; i != s.size(); i++) 
                m[s[i]]++;
            for (int i = 0; i != t.size(); i++) {
                if (m[t[i]] > 0)
                    m[t[i]]--;
                else
                    return t[i];
            }
        }
    };
    // 9 ms

    相关参考:

    [LeetCode] Single Number

  • 相关阅读:
    第04组 Beta冲刺(2/4)
    第04组 Beta冲刺(1/4)
    2019 SDN上机第6次作业
    SDN课程阅读作业(2)
    2019 SDN上机第5次作业
    第04组 Alpha事后诸葛亮
    第04组 Alpha冲刺(4/4)
    2019 SDN上机第4次作业
    第04组 Alpha冲刺(3/4)
    第07组 Alpha冲刺(4/6)
  • 原文地址:https://www.cnblogs.com/immjc/p/7154157.html
Copyright © 2011-2022 走看看