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

  • 相关阅读:
    bzoj 1217: [HNOI2003]消防局的设立
    [USACO09FEB]庙会班车Fair Shuttle
    bzoj 1052: [HAOI2007]覆盖问题
    bzoj 1974: [Sdoi2010]代码拍卖会
    bzoj 1835: [ZJOI2010]基站选址
    bzoj 1875: [SDOI2009]HH去散步
    bzoj 3295: [Cqoi2011]动态逆序对
    bzoj 2120: 数颜色
    P1032 字串变换
    简析拓扑排序
  • 原文地址:https://www.cnblogs.com/immjc/p/7154157.html
Copyright © 2011-2022 走看看