forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindtheDifference.java
61 lines (51 loc) · 1.23 KB
/
FindtheDifference.java
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
class Solution {
public char findTheDifference(String s, String t) {
char ans ='0';
for(char c : s.toCharArray()){
ans ^= c;
}
for(char c : t.toCharArray()){
ans ^= c;
}
ans ^= '0';
return ans;
}
}
//Author: Shobhit Behl (LeetCode:shobhitbruh)
//HashMap Solution (naive approach)
public class Solution {
public char findTheDifference(String s, String t) {
HashMap<Character,Integer> hs=new HashMap<>();
char[] arr=s.toCharArray();
for(char x:arr){
hs.put(x,hs.getOrDefault(x,0)+1);
}
char[] abc=t.toCharArray();
char ans='&';
for(char x:abc){
if(hs.containsKey(x)){
hs.put(x,hs.get(x)-1);
if(hs.get(x)==0){
hs.remove(x);
}
}else{
ans=x;
break;
}
}
return ans;
}
}
// (Optimized) Bit-Manipulation Solution T:O(n+m), where n is s.length() and m is t.length();
public class Solution {
public char findTheDifference(String s, String t) {
char c = 0;
for (int i = 0; i < s.length(); ++i) {
c ^= s.charAt(i);
}
for (int i = 0; i < t.length(); ++i) {
c ^= t.charAt(i);
}
return c;
}
}