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:
1 2 3 4 5 6 7 8 9
|
Input: s = "abcd" t = "abcde"
Output: e
Explanation: 'e' is the letter that was added.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class { public char findTheDifference(String s, String t) { Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < t.length(); i++) { char ch = t.charAt(i); if (map.containsKey(ch)) { int val = map.get(ch); map.put(ch, val + 1); } else { map.put(ch, 1); } } for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (map.containsKey(ch)) { int val = map.get(ch); if (val - 1 <= 0) { map.remove(ch); } else { map.put(ch, val - 1); } } } Character ch = null; Set<Map.Entry<Character, Integer>> entrySet = map.entrySet(); for (Map.Entry<Character, Integer> entry: entrySet) { ch = entry.getKey(); } return ch; } }
|
近期评论