You are given two strings s
and t
.
String t
is generated by random shuffling string s
and then add one more letter at a random position.
Return the letter that was added to 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"
Constraints:
0 <= s.length <= 1000
t.length == s.length + 1
s
andt
consist of lowercase English letters.
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
counter = Counter(s)
for c in t:
if counter[c] <= 0:
return c
counter[c] -= 1
return None
class Solution {
public char findTheDifference(String s, String t) {
int[] counter = new int[26];
for (int i = 0; i < s.length(); ++i) {
int index = s.charAt(i) - 'a';
++counter[index];
}
for (int i = 0; i < t.length(); ++i) {
int index = t.charAt(i) - 'a';
if (counter[index] <= 0) {
return t.charAt(i);
}
--counter[index];
}
return ' ';
}
}
impl Solution {
pub fn find_the_difference(s: String, t: String) -> char {
let s = s.as_bytes();
let t = t.as_bytes();
let n = s.len();
let mut count = [0; 26];
for i in 0..n {
count[(s[i] - b'a') as usize] -= 1;
count[(t[i] - b'a') as usize] += 1;
}
let mut res = *t.last().unwrap();
for i in 0..26 {
if count[i] == 1 {
res = (i as u8) + b'a';
break;
}
}
char::from(res)
}
}