Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
36 lines (27 loc) · 904 Bytes

389.md

File metadata and controls

36 lines (27 loc) · 904 Bytes

389. Find the Difference

Description

Given two strings s and t which consist of only lowercase letters. String t is generated by randomly 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.

Thinking Process

  1. The trick is to use XOR operation, since XOR of the same character will cancel out to 0.
  2. By scanning through both strings and XOR every letter, letters that appear in pairs will eventually cancel out, leaving the added letter behind
public char findTheDifference(String s, String t) {
  	char extraLetter = 0;
    for(int i=0; i<t.length(); i++){
        char c1 = (i < s.length()) ? s.charAt(i) : 0;
        char c2 = t.charAt(i);
        extraLetter ^= (c1 ^ c2);
    }
    return extraLetter;
}