389 Find the Difference
Problem:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.Solutions:
public class Solution {
public char findTheDifference(String s, String t) {
HashMap<Character, Integer> chars = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i ++) {
char c = s.charAt(i);
if (!chars.containsKey(c)) {
chars.put(c, 0);
}
chars.put(c, chars.get(c) + 1);
}
for (int i = 0; i < t.length(); i ++) {
char c = t.charAt(i);
if (!chars.containsKey(c)) {
return c;
}
if (chars.get(c) == 0) {
return c;
}
chars.put(c, chars.get(c) - 1);
}
return ' ';
}
}Last updated