forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTheDifference.java
More file actions
72 lines (66 loc) · 1.64 KB
/
FindTheDifference.java
File metadata and controls
72 lines (66 loc) · 1.64 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
70
71
72
package com.examplehub.leetcode.easy;
import java.util.Arrays;
import java.util.HashSet;
/** https://leetcode.com/problems/find-the-difference/ */
public class FindTheDifference {
public static char solution1(String s, String t) {
char[] firstChars = s.toCharArray();
char[] secondChars = t.toCharArray();
Arrays.sort(firstChars);
Arrays.sort(secondChars);
for (int i = 0; i < firstChars.length; ++i) {
if (firstChars[i] != secondChars[i]) {
return secondChars[i];
}
}
return secondChars[secondChars.length - 1];
}
public static char solution2(String s, String t) {
int[] countTab = new int[26];
for (char ch : s.toCharArray()) {
countTab[ch - 'a']++;
}
for (char ch : t.toCharArray()) {
countTab[ch - 'a']--;
if (countTab[ch - 'a'] < 0) {
return ch;
}
}
return ' ';
}
public static char solution3(String s, String t) {
int sum = 0;
for (char ch : t.toCharArray()) {
sum += ch;
}
for (char ch : s.toCharArray()) {
sum -= ch;
}
return (char) sum;
}
public static char solution4(String s, String t) {
int ret = 0;
for (int i = 0; i < s.length(); ++i) {
ret ^= s.charAt(i);
}
for (int i = 0; i < t.length(); ++i) {
ret ^= t.charAt(i);
}
return (char) ret;
}
public static char solution5(String s, String t) {
s = s + t;
HashSet<Character> set = new HashSet<>();
for (char ch : s.toCharArray()) {
if (set.contains(ch)) {
set.remove(ch);
} else {
set.add(ch);
}
}
for (char ch : set) {
return ch;
}
return ' ';
}
}