
Problem
Solution
Analysis
Python implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class : def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ counter_s = dict() for c in s: counter_s[c] = counter_s.get(c, 0) + 1 for c in t: if not counter_s.get(c, 0): return c counter_s[c] -= 1
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class { public char findTheDifference(String s, String t) { Map<Character, Integer> counter = new HashMap<>(); for(char c : s.toCharArray()) counter.put(c, counter.getOrDefault(c, 0) + 1); for(char c : t.toCharArray()){ if(counter.getOrDefault(c, 0) == 0) return c; counter.put(c, counter.get(c) - 1); } return 0; } }
|
Time complexity
O(n).
Space complexity
O(n).
Link
389. Find the Difference
(中文版) 算法笔记: 力扣#389 找不同
近期评论