Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.
A,Topic describes
- You are given two strings:
ransomNote
和magazine
To determineransomNote
Can you bymagazine
Inside the character composition. - If so, return
true
; Otherwise returnsfalse
。 magazine
Each character in theransomNote
Is used once in.- Example 1:
- Enter: ransomNote = “a”, magazine = “b”
- Output: false
- Example 2:
- Enter: ransomNote = “aa”, magazine = “ab”
- Output: false
- Example 3:
- Enter: ransomNote = “aa”, magazine = “aab”
- Output: true,
- Tip:
1 <= ransomNote. Length, magazine. Length <= math.pow (10,5)
ransomNote
和magazine
Consists of lowercase English letters
Ii. Analysis of Ideas:
ransomNote
bymagazine
The necessary conditions for the formation of characters in it are,ransomNote
The string ismagazine
Subset of strings- We first convert the string to an array of strings that are easier to iterate over
- if
ransomNote
The characters inmagazine
Existence, willmagazine
This character is cut out and saved - Final judgment from
magazine
Whether the truncated character length andransomNote
equal- If the lengths are equal, then
ransomNote
The characters inmagazine
All found, return true - If you don’t want to wait, then
ransomNote
The characters inmagazine
At least one character cannot be found, return false
- If the lengths are equal, then
Iii. AC Code:
function canConstruct(ransomNote: string, magazine: string) :boolean {
let ransomNoteArr = ransomNote.split(' ');
let magazineArr = magazine.split(' ');
let resultArr = [];
for(let i = 0; i < ransomNoteArr.length; i++){
for(let j = 0; j < magazineArr.length; j++){
if(ransomNoteArr[i] === magazineArr[j]){
resultArr.push(magazineArr.splice(j, 1) [0]);
j--;
break; }}}if(resultArr.length === ransomNoteArr.length){
return true
}
return false
};
Copy the code
Iv. Summary:
- One thing to notice is arrays
splice
Method changes the length of the original array, so intercepts the subsequent loop argumentj
Need to minus1
- Because the title requires that each character be used only once, so once in
magazine
Find the first andransomNote
After the characters are equal and truncated, the current loop should be immediately exited. Otherwise, equal characters will be intercepted twice later, so the truncatedbreak
Operation matters - There are other ways that are less complicated, if you want to go to the solution section