头图

title: Daily Practice (47): Find the Difference

categories:[Swords offer]

tags:[Daily practice]

date: 2022/04/22


Daily practice (47): Find the difference

Given two strings s and t, they contain only lowercase letters. String t is randomly rearranged from string s, and then a letter is added at a random position. Find the letter that was added in the t.

Example 1:

Input: s = "abcd", t = "abcde"

output: "e"

Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y"

output: "y"

hint:

0 <= s.length <= 1000

t.length == s.length + 1

s and t contain only lowercase letters

Source: LeetCode

Link: https://leetcode-cn.com/problems/find-the-difference

Method 1: Summation

Thought analysis

This question is to add only one character, find the ASCII value of the s string and the ASCII value of t and then the ASCII value of t - s to get the ASCII value of the added character

 char findTheDifference(string s, string t) {
    int as = 0, at = 0;
    for (auto ch : s) {
        as += ch;
    }
    for (auto ch : t) {
        at += ch;
    }
    return at - as;
}

Method 2: Bit Operations

Thought analysis

If two strings are concatenated into one string, the problem turns into finding the odd number of characters in the string

Features of the XOR operation:

  • XOR itself to 0, and XOR 0 to itself;
  • It has commutative and associative laws, such as 1^2^3^4^2^3^1 = (1^1)^(2^2)^(3^3)^4 = 0^0^0^4 = 0^4 = 4;
  • Summary: The XOR operation is good at finding differences.
 char findTheDifference(string s, string t) {
    int ret = 0;
    for (auto ch : s) {
        ret ^= ch;
    }
    for (auto ch : t) {
        ret ^= ch;
    }
    return ret;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记