Leetcode 389. Find the Difference
You are given two strings s and t. String t is generated by random shuffling string s and then adding one more letter at a random position.
Return the letter that was added to t.
Example:
Input: s = "abcd", t = "abcde"
Output: "e"
s and t always non-empty?
s and t are non-empty strings, with t having exactly one more character than s.t than in s?
t will always have exactly one more character than s.count of size 26 to store the frequencies of each letter (a to z).s and decrement the frequency count for each character found in s.t and increment the frequency count for each character found in t.count array to find the character with a count of 1, which is the additional character in t.charCode to 0.s and t. Due to the properties of XOR, characters that appear twice will cancel out and only the additional character will remain in charCode.charCode to the corresponding character.We’ll go with Approach 2 since it is more efficient and elegant.
public class Solution {
public char findTheDifference(String s, String t) {
int charCode = 0;
for (char c : s.toCharArray()) {
charCode ^= c;
}
for (char c : t.toCharArray()) {
charCode ^= c;
}
return (char) charCode;
}
}
s. We process each character in string s and t once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?