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

  • 相关阅读:
    hdu 1998 奇数阶魔方(找规律+模拟)
    巧用百度Site App新组件为企业官网打造移动站
    POJ 1276 Cash Machine
    Unity3D中使用MiniJson解析json的例子
    设计模式读书笔记-----单例模式
    android 常用资料
    Objective-C之run loop详解
    icon 图标下载
    揭开Html 标签的面纱,忘不了的html .
    12157
  • 原文地址:https://www.cnblogs.com/immjc/p/7154157.html
Copyright © 2011-2022 走看看