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 和 magazineTo determineransomNoteCan you bymagazineInside the character composition.
  • If so, returntrue; Otherwise returnsfalse 。
  • magazineEach character in theransomNoteIs 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 和 magazineConsists of lowercase English letters

Ii. Analysis of Ideas:

  • ransomNotebymagazineThe necessary conditions for the formation of characters in it are,ransomNoteThe string ismagazineSubset of strings
  • We first convert the string to an array of strings that are easier to iterate over
  • ifransomNoteThe characters inmagazineExistence, willmagazineThis character is cut out and saved
  • Final judgment frommagazineWhether the truncated character length andransomNoteequal
    • If the lengths are equal, thenransomNoteThe characters inmagazineAll found, return true
    • If you don’t want to wait, thenransomNoteThe characters inmagazineAt least one character cannot be found, return false

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 arraysspliceMethod changes the length of the original array, so intercepts the subsequent loop argumentjNeed to minus1
  • Because the title requires that each character be used only once, so once inmagazineFind the first andransomNoteAfter the characters are equal and truncated, the current loop should be immediately exited. Otherwise, equal characters will be intercepted twice later, so the truncated breakOperation matters
  • There are other ways that are less complicated, if you want to go to the solution section