LeetCode 389. Find the Difference #84
quinnwencn
started this conversation in
General
Replies: 1 comment 1 reply
-
AnalysisSame as previous problem, we use an array to record the number of characters and compare with later string. Solution written in Rustimpl Solution {
pub fn find_the_difference(s: String, t: String) -> char {
let mut alphas = [0; 26];
s.chars().for_each(|c| {
let i = c as usize - 'a' as usize;
alphas[i] += 1;
});
for c in t.chars() {
let i = c as usize - 'a' as usize;
if alphas[i] == 0 {
return c;
}
alphas[i] -= 1;
}
' '
}
}Solution written in Cppclass Solution {
public:
char findTheDifference(string s, string t) {
std::array<uint16_t, 26> chars {0};
for (auto c: s) {
chars[c - 'a']++;
}
for (auto c: t) {
if (chars[c - 'a'] == 0) {
return c;
}
chars[c - 'a']--;
}
return ' ';
}
}; |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y"
Output: "y"
Constraints:
0 <= s.length <= 1000
t.length == s.length + 1
s and t consist of lowercase English letters.
Beta Was this translation helpful? Give feedback.
All reactions