-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path389.find-the-difference.go
More file actions
69 lines (64 loc) · 1.25 KB
/
389.find-the-difference.go
File metadata and controls
69 lines (64 loc) · 1.25 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* @lc app=leetcode id=389 lang=golang
*
* [389] Find the Difference
*
* https://leetcode.com/problems/find-the-difference/description/
*
* algorithms
* Easy (54.93%)
* Likes: 843
* Dislikes: 285
* Total Accepted: 201K
* Total Submissions: 363.5K
* Testcase Example: '"abcd"\n"abcde"'
*
*
* 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:
*
* Input:
* s = "abcd"
* t = "abcde"
*
* Output:
* e
*
* Explanation:
* 'e' is the letter that was added.
*
*/
// @lc code=start
func findTheDifference(s string, t string) byte {
return findTheDifference2(s, t)
}
// https://leetcode.com/problems/find-the-difference/discuss/593690/XOR-golang-solution
// XOR solution
func findTheDifference2(s string, t string) byte {
var res byte
for _, v := range []byte(s + t) {
res ^= v
}
return res
}
func findTheDifference1(s string, t string) byte {
hash := map[byte]int{}
for _, v := range s {
hash[byte(v)]++
}
for _, v := range t {
if k, ok := hash[byte(v)]; ok && k > 0 {
hash[byte(v)]--
} else {
return byte(v)
}
}
return 0
}
// @lc code=end