算法笔记: 力扣#389 找不同

问题描述


解法


分析

Python 实现

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 实现

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;
}
}

时间复杂度

O(n).

空间复杂度

O(n).

链接


389. Find the Difference
389. 找不同
(English version) Algorithm Notes: Leetcode#389 Find the Difference