LeetCode 383. Ransom Note #82
quinnwencn
started this conversation in
General
Replies: 1 comment
-
AnalysisThere are only lowercase English letters in both magazine and ransomNotes. We can use a 26-sized array to calculate the number of letters in magazine and compare them with ransomNotes. Solution written in CppSolution written in Rustimpl Solution {
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
let mut count: [i32; 26] = [0; 26];
magazine
.chars()
.for_each(|char| {
let index = char as usize - 'a' as usize;
count[index] += 1;
});
let mut res = true;
ransom_note
.chars()
.for_each(|char| {
let index = char as usize - 'a' as usize;
if count[index] == 0 {
res = false;
} else {
count[index] -= 1;
}
});
res
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
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
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine consist of lowercase English letters.
Beta Was this translation helpful? Give feedback.
All reactions