publicclassSolution {
publiccharfindTheDifference(String s, String t) {
int n = s.length();
// Convert strings to character arrays and sort themchar[] sArray = s.toCharArray();
char[] tArray = t.toCharArray();
Arrays.sort(sArray);
Arrays.sort(tArray);
// Compare characters in the sorted arraysfor (int i = 0; i < n; i++) {
if (sArray[i]!= tArray[i]) {
return tArray[i];
}
}
// If no mismatch found in the first n characters, return the last character of treturn tArray[n];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
deffindTheDifference(self, s: str, t: str) -> str:
# Convert strings to lists of characters and sort them s_array: List[str] = sorted(s)
t_array: List[str] = sorted(t)
# Compare characters in the sorted arraysfor i in range(len(s)):
if s_array[i] != t_array[i]:
return t_array[i]
# If no mismatch found in the first n characters, return the last character of treturn t_array[len(s)]
classSolution:
deffindTheDifference(self, s: str, t: str) -> str:
count_map = defaultdict(int)
# Increase count for each character in sfor char in s:
count_map[char] +=1# Decrease count for each character in tfor char in t:
count_map[char] -=1if count_map[char] <0:
return char
return''
publiccharfindTheDifference(String s, String t) {
int n = t.length();
char c = t.charAt(n - 1);
for (int i = 0; i < n - 1; ++i) {
c ^= s.charAt(i);
c ^= t.charAt(i);
}
return c;
}
1
2
3
4
5
6
classSolution:
deffindTheDifference(self, s: str, t: str) -> str:
ans: str = t[-1]
for i in range(len(t) -1):
ans = chr(ord(ans) ^ ord(s[i]) ^ ord(t[i]))
return ans