Skip to content

Latest commit

 

History

History
62 lines (48 loc) · 1.08 KB

File metadata and controls

62 lines (48 loc) · 1.08 KB

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.

Solutions (Rust)

1. Count

impl Solution {
    pub fn find_the_difference(s: String, t: String) -> char {
        let mut cnt = [0; 26];

        for ch in s.bytes() {
            cnt[(ch - b'a') as usize] += 1;
        }

        for ch in t.bytes() {
            cnt[(ch - b'a') as usize] -= 1;
            if cnt[(ch - b'a') as usize] == -1 {
                return ch as char;
            }
        }

        ' '
    }
}

2. XOR

impl Solution {
    pub fn find_the_difference(s: String, t: String) -> char {
        let mut ret = 0;

        for ch in s.bytes() {
            ret ^= ch;
        }

        for ch in t.bytes() {
            ret ^= ch;
        }

        ret as char
    }
}